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 avk_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
-
self_bot
¶ If
True
, the bot will only listen to commands invoked by itself rather than ignoring itself. IfFalse
(the default) then the bot will ignore itself. This cannot be changed once initialised.- Type
-
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
-
add_check
(func, *, call_once=False)¶ Adds a global check to the bot. This is the non-decorator interface to
check()
andcheck_once()
.- Parameters
func – The function that was used as a global check.
call_once (
bool
) – If the function should only be called once perCommand.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
CommandError – An error happened during loading.
-
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
ClientException – If the command is already registered.
TypeError – If the command passed is not a subclass of
Command
.
-
add_listener
(func, name=None)¶ The non decorator alternative to
listen()
.- Parameters
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.
-
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()
andafter_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.
-
exception
botCommandException
¶ -
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
-
build_msg
(msg)¶ Build
Message
instance from message objectdict
.Normally should not be used at all.
-
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 typeContext
and can only raise exceptions inherited fromCommandError
. .. 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 orCommand.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 typeContext
and can only raise exceptions inherited fromCommandError
.Example
@bot.check_once def whitelist(ctx): return ctx.message.author.id in my_whitelist
-
command
(*args, **kwargs)¶ A shortcut decorator that invokes
command()
and adds it to the internal command list viaadd_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 subcommandbar
of the group commandfoo
. If a subcommand is not found thenNone
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 underinvoke()
.- Parameters
- Returns
The invocation context. The type of this can change via the
cls
parameter.- Return type
-
await
get_group
(gid)¶ This function is a coroutine.
Alias for VK Api ‘groups.get’ method call that returns only one group.
-
await
get_own_page
()¶ This function is a coroutine.
Gets page for current token, whether it is Group or 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
- Raises
vk_botting.VKApiError – When error is returned by VK API.
- Returns
- Return type
-
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
- Raises
vk_botting.VKApiError – When error is returned by VK API.
- Returns
- Return type
-
await
get_prefix
(message)¶ This function is a coroutine.
Retrieves the prefix the bot is listening to with the message as a context.
-
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
- Raises
vk_botting.VKApiError – When error is returned by VK API.
- Returns
User
instance for requested user- Return type
-
await
get_users
(*uids, fields=None, name_case=None)¶ This function is a coroutine.
Alias for VK Api ‘users.get’ method call
-
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, thebot
.- 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 importfoo/test.py
.- Raises
ExtensionNotFound – The extension could not be imported.
ExtensionAlreadyLoaded – The extension is already loaded.
NoEntryPointError – The extension does not have a setup function.
ExtensionFailed – The extension or its setup function had an execution error.
-
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 theon_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 toinvoke()
.This also checks if the message’s author is a bot and doesn’t call
get_context()
orinvoke()
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 aload_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 importfoo/test.py
.- Raises
ExtensionNotLoaded – The extension was not loaded.
ExtensionNotFound – The extension could not be imported.
NoEntryPointError – The extension does not have a setup function.
ExtensionFailed – The extension setup function had an execution error.
-
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 withcall_once=True
in theBot.add_check()
call or usingcheck_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.
-
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 tofunc.__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.
-
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 theattachment
orsticker_id
parameter must be provided.If the
attachment
parameter is provided, it must bestr
, List[str
],Attachment
or List[Attachment
]If the
keyboard
parameter is provided, it must bestr
orKeyboard
(recommended)- Parameters
peer_id (
int
) – Id of conversation to send message tomessage (
str
) – The text of the message to send.attachment (Union[List[
str
],str
, List[Attachment
],Attachment
]) – The attachment to the message sent.keyboard (
Keyboard
) – The keyboard to send along message.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
-
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, thebot
, similar tosetup
fromload_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 importfoo/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 fromDocType
enum.title (
str
) – Title for uploaded document. Filename by default.
- Returns
Attachment
instance representing uploaded document.- Return type
-
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
-
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
-
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 recommendedkwargs (
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
-
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 recommendedkwargs (
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
-
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 ontoasyncio.wait_for()
. By default, it does not timeout. Note that this does propagate theasyncio.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 theon_
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 raisingasyncio.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.-
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
-
kwargs
¶ A dictionary of transformed arguments that were passed into the command. Similar to
args
, if this is accessed in theon_command_error()
event then this dict could be incomplete.- Type
-
invoked_with
¶ The command name that triggered this invocation. Useful for finding out which alias called the command.
- Type
-
invoked_subcommand
¶ The subcommand (i.e.
Command
or its subclasses) that was invoked. If no valid subcommand was invoked then this is equal toNone
.
-
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
-
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 regularinvoke()
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.
-
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
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()
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.
Shorthand for
Message.from_id
-
from_id
¶ Shorthand for
Message.from_id
-
peer_id
¶ Shorthand for
Message.peer_id
-
text
¶ Shorthand for
Message.text
-
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 theattachment
orsticker_id
parameter must be provided.If the
attachment
parameter is provided, it must bestr
, List[str
],Attachment
or List[Attachment
]If the
keyboard
parameter is provided, it must bestr
orKeyboard
(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.keyboard (
Keyboard
) – The keyboard to send along message.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
-
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
-
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
andasync 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 anon_error
handler consisting of a single empty The raise statement. Exceptions raised byon_error
will not be handled in any way byBot
.- 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.
-
on_chat_invite_user_by_link
(message)¶ 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.
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.-
for ... in
walk_commands
()¶ An iterator that recursively walks through this cog’s commands and subcommands.
-
classmethod
listener
(name=None)¶ A decorator that marks a function as a listener.
This is the cog equivalent of
Bot.listen()
.
-
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 theContext
.
-
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 theContext
.
-
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 theContext
.
-
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.
-
for ... in
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
-
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
-
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
andasync 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 theattachment
orsticker_id
parameter must be provided.If the
attachment
parameter is provided, it must bestr
, List[str
],Attachment
or List[Attachment
]If the
keyboard
parameter is provided, it must bestr
orKeyboard
(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.keyboard (
Keyboard
) – The keyboard to send along message.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
-
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
-
async with
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 toBot.send_message()
-
type
¶ Type of an attachment. Can be value from
AttachmentType
enum.- Type
-
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-
classmethod
get_empty_keyboard
()¶ Classmethod for getting empty keyboard. Useful when keyboard should be cleared
Adds button to current line
- Parameters
label (
str
) – Button label to be displayedcolor (:class:Union[str, KeyboardColor]) – Button color. Can be value from
KeyboardColor
enumpayload (
dict
) – Optional. Should be used for some buttons
- Raises
vk_botting.VKApiError – When there are already too many buttons on one line
Adds a callback button (https://vk.com/dev/bots_docs_5) to current line
- Parameters
label (
str
) – Button label to be displayedcolor (:class:Union[str, KeyboardColor]) – Button color. Can be value from
KeyboardColor
enumpayload (
dict
) – Optional. Should be used for some buttons
- Raises
vk_botting.VKApiError – When there are already too many buttons on one line
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
Adds button to current line
Adds button to current line
- Parameters
- 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
-
classmethod
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 typeBucketType
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 inon_command_error()
and the local error handler.A command can only have a single cooldown.
-
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.
-
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
andasync 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 theattachment
orsticker_id
parameter must be provided.If the
attachment
parameter is provided, it must bestr
, List[str
],Attachment
or List[Attachment
]If the
keyboard
parameter is provided, it must bestr
orKeyboard
(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.keyboard (
Keyboard
) – The keyboard to send along message.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
-
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
-
async with
Group¶
-
class
vk_botting.group.
Group
(data)¶ Represents a VK Group
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
-
date
¶ Datetime when message was sent
- Type
-
update_time
¶ Datetime when message was updated
- Type
-
attachments
¶ List of attachments delivered with message
- Type
List[
Attachment
]
-
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
andasync 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 toTrue
keep_snippets (
bool
) –True
if snippets should be kept. Defaults toTrue
- Raises
vk_botting.VKApiError – When error is returned by VK API.
- Returns
The message that was sent.
- Return type
-
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 toTrue
- 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 theattachment
orsticker_id
parameter must be provided.If the
attachment
parameter is provided, it must bestr
, List[str
],Attachment
or List[Attachment
]If the
keyboard
parameter is provided, it must bestr
orKeyboard
(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.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
-
await
get_user
()¶ This function is a coroutine. Returns the author of original message as instance of
User
class
This function is a coroutine. Alternative for
Message.get_user()
-
await
fetch_user
()¶ This function is a coroutine. Alternative for
Message.get_user()
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 theattachment
orsticker_id
parameter must be provided.If the
attachment
parameter is provided, it must bestr
, List[str
],Attachment
or List[Attachment
]If the
keyboard
parameter is provided, it must bestr
orKeyboard
(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.keyboard (
Keyboard
) – The keyboard to send along message.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
-
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
-
MessageEvent¶
-
class
vk_botting.message.
MessageEvent
(data)¶ Represents a message event (https://vk.com/dev/bots_docs_5).
-
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
-
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).
-
await
open_link
(link)¶ This function is a coroutine.
Coroutine to send an open_link answer to the event (opens certain link).
-
await
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
, andtype
similar to thecooldown()
decorator.- Type
Cooldown
-
-
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 fromArgumentError
-
param
¶ The parameter that failed being converted.
- Type
-
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
-
-
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 toTrue
.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
.
-
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
-
class
vk_botting.exceptions.
ExtensionNotFound
(name, original)¶ An exception raised when an extension is not found.
This inherits from
ExtensionError
-
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
.
-
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
.
-
class
vk_botting.exceptions.
ExpectedClosingQuoteError
(close_quote)¶ An exception raised when a quote character is expected but not found.
This inherits from
ArgumentError
.
-
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.
-
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
ClientException – If the command is already registered.
TypeError – If the command passed is not a subclass of
Command
.
-
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.
-
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 subcommandbar
of the group commandfoo
. If a subcommand is not found thenNone
is returned just as usual.
-
command
(*args, **kwargs)¶ A shortcut decorator that invokes
command()
and adds it to the internal command list viaadd_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.
-
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 theon_command_error()
event. Defaults toTrue
.- Type
-
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 fromCommandError
should be used. Note that if the checks fail thenCheckFailure
exception is raised to theon_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 handlesMissingRequiredArgument
and default values in a regular matter rather than passing the rest completely raw. IfTrue
then the keyword-only argument will pass in the rest of the arguments in a completely raw matter. Defaults toFalse
.- Type
-
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 expectinga
andb
). Otherwiseon_command_error()
and local error handlers are called withTooManyArguments
. Defaults toTrue
.- Type
-
cooldown_after_parsing
¶ If
True
, cooldown processing is done after argument parsing, which calls converters. IfFalse
then cooldown processing is done first and then the converters are called second. Defaults toFalse
.- Type
-
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 theCommand
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 beone two
.- Type
-
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
-
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 isa
.
-
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 beone two three
.- Type
-
is_on_cooldown
(ctx)¶ Checks whether the command is currently on cooldown.
-
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, theon_command_error()
is still invoked afterwards as the catch-all.
-
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.
-
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.
-
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
-
-
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 ontoasyncio.wait_for()
. By default, it does not timeout. Note that this does propagate theasyncio.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 theon_
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 raisingasyncio.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 recommendedkwargs (
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
-
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 recommendedkwargs (
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
-
await
get_users
(*uids, fields=None, name_case=None)¶ This function is a coroutine.
Alias for VK Api ‘users.get’ method call
-
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
- Raises
vk_botting.VKApiError – When error is returned by VK API.
- Returns
- Return type
-
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
- Raises
vk_botting.VKApiError – When error is returned by VK API.
- Returns
User
instance for requested user- Return type
-
await
get_group
(gid)¶ This function is a coroutine.
Alias for VK Api ‘groups.get’ method call that returns only one 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
- Raises
vk_botting.VKApiError – When error is returned by VK API.
- Returns
- Return type
-
await
get_own_page
()¶ This function is a coroutine.
Gets page for current token, whether it is Group or 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
-
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 fromDocType
enum.title (
str
) – Title for uploaded document. Filename by default.
- Returns
Attachment
instance representing uploaded document.- Return type
-
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
-
build_msg
(msg)¶ Build
Message
instance from message objectdict
.Normally should not be used at all.
-
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 theattachment
orsticker_id
parameter must be provided.If the
attachment
parameter is provided, it must bestr
, List[str
],Attachment
or List[Attachment
]If the
keyboard
parameter is provided, it must bestr
orKeyboard
(recommended)- Parameters
peer_id (
int
) – Id of conversation to send message tomessage (
str
) – The text of the message to send.attachment (Union[List[
str
],str
, List[Attachment
],Attachment
]) – The attachment to the message sent.keyboard (
Keyboard
) – The keyboard to send along message.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
-
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.
-
exception
-
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
- Raises
TypeError – If the function is not a coroutine or is already a command.