disnake
85 строк · 2.5 Кб
1# SPDX-License-Identifier: MIT
2
3"""An example using converters with slash commands."""
4
5import os
6
7import disnake
8from disnake.ext import commands
9
10bot = commands.Bot(command_prefix=commands.when_mentioned)
11
12
13# Classic commands.Converter classes have been replaced by more user-friendly converter functions,
14# which can be set using `Param` and the `converter` argument.
15@bot.slash_command()
16async def clean_command(
17inter: disnake.CommandInteraction[commands.Bot],
18text: str = commands.Param(converter=lambda inter, text: text.replace("@", "\\@")),
19):
20...
21
22
23# Converters may also set the type of the option using annotations.
24# Here the converter (and therefore, the slash command) is actually using a user option,
25# while the command callback will receive a str.
26def avatar_converter(inter: disnake.CommandInteraction, user: disnake.User) -> str:
27return user.display_avatar.url
28
29
30@bot.slash_command()
31async def command_with_avatar(
32inter: disnake.CommandInteraction,
33avatar: str = commands.Param(converter=avatar_converter),
34):
35...
36
37
38# Converting to custom classes is also very easy using class methods.
39class SomeCustomClass:
40def __init__(self, username: str, discriminator: str) -> None:
41self.username = username
42self.discriminator = discriminator
43
44@classmethod
45async def from_option(cls, inter: disnake.CommandInteraction, user: disnake.User):
46return cls(user.name, user.discriminator)
47
48
49@bot.slash_command()
50async def command_with_clsmethod(
51inter: disnake.CommandInteraction,
52some: SomeCustomClass = commands.Param(converter=SomeCustomClass.from_option),
53):
54...
55
56
57# An even better approach is to register a method as the class converter,
58# to be able to use only an annotation for the slash command option.
59# `@converter_method` works like `@classmethod`,
60# except it also stores the converter callback in an internal registry.
61class OtherCustomClass:
62def __init__(self, username: str, discriminator: str) -> None:
63self.username = username
64self.discriminator = discriminator
65
66@commands.converter_method
67async def convert(cls, inter: disnake.CommandInteraction, user: disnake.User):
68return cls(user.name, user.discriminator)
69
70
71@bot.slash_command()
72async def command_with_convmethod(
73inter: disnake.CommandInteraction,
74other: OtherCustomClass,
75):
76...
77
78
79@bot.event
80async def on_ready():
81print(f"Logged in as {bot.user} (ID: {bot.user.id})\n------")
82
83
84if __name__ == "__main__":
85bot.run(os.getenv("BOT_TOKEN"))
86