Search code examples
discorddiscord.py

AttributeError: module 'discord.ext.commands' has no attribute 'OptionChoice'


I am trying to create a discord bot with slash commands, and when I try to incorporate more complex sections in my command (E.g: /online [server]). I know, that I need the module "Options". The Problem is, not sure where to import this "Options"... "discord.ext"? "discord"? "discord.commands"?

Here is the error: AttributeError: module 'discord.ext.commands' has no attribute 'Option'

Here is the interested code part:

@bot.tree.command(name="online",description="Set your online status and server.")
async def online(interaction: discord.Interaction, server: Option(choices=[
                        ("EU1", "EU1"),
                        ("EU2", "EU2"),
                        ("US1", "US1"),
                        ("US2", "US2"),
                        ("SEA", "SEA"),
                ])):
    await interaction.response.send_message(f"You chose {server} as your server.")

these are my current imports:

import discord
from discord.ext import commands
from discord.ext.commands import Option
from discord.ui import Select
from datetime import datetime, timedelta
import asyncio
from discord import app_commands
import pickle
import json
import time
from threading import Thread

I tried every possible Discord Module, but with no success. I doubt its an error in the code, but let me know!


Solution

  • You need a decorator for the choices list and need to clarify that as an argument type inside the command args.

    In order to create the choices list first, you need to create a decorator above your command function:

    
    @app_commands.choices=(server=[app_commands.Choice(name="EU1", value="EU1"),
                                   app_commands.Choice(name="EU2", value="EU2"),
                                   app_commands.Choice(name="US1", value="US1"),
                                   app_commands.Choice(name="US2", value="US2"),
                                   app_commands.Choice(name="SEA", value="SEA")])
    

    After that, you need to create the argname argument in your slash command itself:

    async def online(interaction: discord.Interaction, server: app_commands.Choice[str])
    

    And these are the only imports that you need to let that code part work:

    from discord.app_commands import Choice
    from discord.ext import commands
    from discord import app_commands
    

    If you want to access the value that the command author picked, you can use server.value in the function.