disnake

Форк
0
/
converters.py 
85 строк · 2.5 Кб
1
# SPDX-License-Identifier: MIT
2

3
"""An example using converters with slash commands."""
4

5
import os
6

7
import disnake
8
from disnake.ext import commands
9

10
bot = 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()
16
async def clean_command(
17
    inter: disnake.CommandInteraction[commands.Bot],
18
    text: 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.
26
def avatar_converter(inter: disnake.CommandInteraction, user: disnake.User) -> str:
27
    return user.display_avatar.url
28

29

30
@bot.slash_command()
31
async def command_with_avatar(
32
    inter: disnake.CommandInteraction,
33
    avatar: str = commands.Param(converter=avatar_converter),
34
):
35
    ...
36

37

38
# Converting to custom classes is also very easy using class methods.
39
class SomeCustomClass:
40
    def __init__(self, username: str, discriminator: str) -> None:
41
        self.username = username
42
        self.discriminator = discriminator
43

44
    @classmethod
45
    async def from_option(cls, inter: disnake.CommandInteraction, user: disnake.User):
46
        return cls(user.name, user.discriminator)
47

48

49
@bot.slash_command()
50
async def command_with_clsmethod(
51
    inter: disnake.CommandInteraction,
52
    some: 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.
61
class OtherCustomClass:
62
    def __init__(self, username: str, discriminator: str) -> None:
63
        self.username = username
64
        self.discriminator = discriminator
65

66
    @commands.converter_method
67
    async def convert(cls, inter: disnake.CommandInteraction, user: disnake.User):
68
        return cls(user.name, user.discriminator)
69

70

71
@bot.slash_command()
72
async def command_with_convmethod(
73
    inter: disnake.CommandInteraction,
74
    other: OtherCustomClass,
75
):
76
    ...
77

78

79
@bot.event
80
async def on_ready():
81
    print(f"Logged in as {bot.user} (ID: {bot.user.id})\n------")
82

83

84
if __name__ == "__main__":
85
    bot.run(os.getenv("BOT_TOKEN"))
86

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.