Skip to content

Commit ebb1904

Browse files
committed
🚚 Add partial autocomplete example
1 parent 7308d08 commit ebb1904

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
from functools import partial
2+
from os import getenv
3+
4+
from dotenv import load_dotenv
5+
6+
import discord
7+
from discord.ext import commands
8+
9+
load_dotenv()
10+
11+
bot = discord.Bot()
12+
13+
fruits = ["Apple", "Banana", "Orange"]
14+
vegetables = ["Carrot", "Lettuce", "Potato"]
15+
16+
17+
async def food_autocomplete(
18+
ctx: discord.AutocompleteContext, food_type: str
19+
) -> list[discord.OptionChoice]:
20+
items = fruits if food_type == "fruit" else vegetables
21+
return [
22+
discord.OptionChoice(name=item)
23+
for item in items
24+
if ctx.value.lower() in item.lower()
25+
]
26+
27+
28+
class FoodCog(commands.Cog):
29+
@commands.slash_command(name="fruit")
30+
async def get_fruit(
31+
self,
32+
ctx: discord.ApplicationContext,
33+
choice: discord.Option(
34+
str,
35+
"Pick a fruit",
36+
autocomplete=partial(food_autocomplete, food_type="fruit"),
37+
),
38+
):
39+
await ctx.respond(f"You picked: {choice}")
40+
41+
@commands.slash_command(name="vegetable")
42+
async def get_vegetable(
43+
self,
44+
ctx: discord.ApplicationContext,
45+
choice: discord.Option(
46+
str,
47+
"Pick a vegetable",
48+
autocomplete=partial(food_autocomplete, food_type="vegetable"),
49+
),
50+
):
51+
await ctx.respond(f"You picked: {choice}")
52+
53+
54+
bot.add_cog(FoodCog())
55+
bot.run(getenv("TOKEN"))

0 commit comments

Comments
 (0)