### Basic Interactions.py Bot Setup Source: https://github.com/interactions-py/interactions.py/blob/stable/README.md This snippet shows the fundamental setup for an interactions.py bot, including client initialization, a startup listener, and starting the bot with a token. Ensure you replace 'token' with your actual bot token. ```python import interactions bot = interactions.Client() @interactions.listen() async def on_startup(): print("Bot is ready!") bot.start("token") ``` -------------------------------- ### Start Task using Decorator on Startup Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/40 Tasks.md This example shows how to start a task defined with a decorator when the bot client starts up. The `on_startup` event listener is used for this. ```python from interactions import Client, Intents, Task, IntervalTrigger, listen @Task.create(IntervalTrigger(minutes=10)) async def print_every_ten(): print("It's been 10 minutes!") bot = Client(intents=Intents.DEFAULT) @listen() async def on_startup(): # (1)! print_every_ten.start() ``` -------------------------------- ### Extension with `__init__` and `setup` Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/20 Extensions.md While not strictly necessary, you can include `__init__` and `setup` functions for more explicit control or compatibility with older patterns. The `setup` function should instantiate the extension. ```python from interactions import Extension class MyExtension(Extension): def __init__(self, bot): self.bot = bot def setup(bot): # yes, the bot does not need to do any special logic - you just need to pass it into the extension MyExtension(bot) ``` -------------------------------- ### Main Bot Setup and Event Handling Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/90 Example.md This snippet shows the basic setup for an interactions.py bot, including defining intents, setting up a logger, and registering event listeners for 'ready', 'guild_create', 'message_create', and 'component' events. It also demonstrates loading extensions and starting the bot. ```python import logging from interactions import Client, Intents, listen from interactions.api.events import Component from interactions.ext import prefixed_commands # define your own logger with custom logging settings logging.basicConfig() cls_log = logging.getLogger("MyLogger") cls_log.setLevel(logging.DEBUG) bot = Client( intents=Intents.DEFAULT | Intents.MESSAGE_CONTENT, sync_interactions=True, asyncio_debug=True, logger=cls_log ) prefixed_commands.setup(bot) @listen() async def on_ready(): print("Ready") print(f"This bot is owned by {bot.owner}") @listen() async def on_guild_create(event): print(f"guild created : {event.guild.name}") # Message content is a privileged intent. # Ensure you have message content enabled in the Developer Portal for this to work. @listen() async def on_message_create(event): print(f"message received: {event.message.content}") @listen() async def on_component(event: Component): ctx = event.ctx await ctx.edit_origin("test") bot.load_extension("test_components") bot.load_extension("test_application_commands") bot.start("Token") ``` -------------------------------- ### Basic Client Setup Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/80 Sharding.md This is a standard client setup before implementing sharding. Ensure you have the necessary imports. ```python from interactions import Client, listen class Bot(Client): async def on_ready(self): print("Ready") print(f"This bot is owned by {self.owner}") @listen() async def on_message_create(self, event): print(f"message received: {event.message.content}") ``` -------------------------------- ### Asynchronous Initialization Example with `asyncio.run` Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/20 Extensions.md This example demonstrates how to correctly use `asyncio.create_task` by loading extensions within an asynchronous function and using `await bot.astart()`, ensuring an event loop is available. ```python bot = Client(...) async def main(): # event loop made! bot.load_extension("extension") await bot.astart("token") asyncio.run(main()) ``` -------------------------------- ### Start Manually Registered Task on Startup Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/40 Tasks.md This demonstrates starting a manually registered task when the bot client begins. The `start()` method is called on the `Task` object within the `on_startup` listener. ```python from interactions import Client, Intents, Task, IntervalTrigger, listen async def print_every_ten(): print("It's been 10 minutes!") bot = Client(intents=Intents.DEFAULT) task = Task(print_every_ten, IntervalTrigger(minutes=10)) @listen() async def on_startup(): task.start() ``` -------------------------------- ### Install Interactions.py Source: https://context7.com/interactions-py/interactions.py/llms.txt Install the Interactions.py library using pip. Optional extras like voice support can be installed with additional package names. ```bash pip install -U discord-py-interactions # Optional extras pip install discord-py-interactions[voice] # voice support (PyNaCl + cryptography) ``` -------------------------------- ### Custom Extension Setup Function Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/20 Extensions.md Implement a `setup` function outside of an `Extension` subclass to perform custom logic when an extension is loaded. This function receives the bot instance and can be used to initialize `Extension` subclasses or perform other setup tasks. ```python from interactions import Extension, Client class MyExtension(Extension): ... def setup(bot: Client): # insert logic here MyExtension(bot) ``` -------------------------------- ### Extension Example Source: https://context7.com/interactions-py/interactions.py/llms.txt Demonstrates how to organize commands and listeners into separate files using Extensions. ```APIDOC ## Extensions — Organizing Code ### Description `Extension` subclasses group commands and listeners into separate files. They can be loaded, reloaded, and unloaded at runtime without restarting the bot. ### Class Definition `class Moderation(Extension):` ### Initialization (`__init__`) - `self.add_ext_check(self.guild_only_check)`: Adds a check that runs before commands in the extension. - `self.add_extension_prerun(self.log_invocation)`: Adds a function to run before each command in the extension. - `self.set_extension_error(self.handle_error)`: Sets a custom error handler for the extension. - `self.add_ext_auto_defer(enabled=True, ephemeral=True, time_until_defer=0.5)`: Automatically defers commands if they take too long. ### Example `cogs/moderation.py` ```python import datetime from interactions import Extension, slash_command, SlashContext, BaseContext, Client class Moderation(Extension): def __init__(self, bot: Client): self.add_ext_check(self.guild_only_check) self.add_extension_prerun(self.log_invocation) self.set_extension_error(self.handle_error) self.add_ext_auto_defer(enabled=True, ephemeral=True, time_until_defer=0.5) async def guild_only_check(self, ctx: BaseContext) -> bool: return ctx.guild is not None async def log_invocation(self, ctx: BaseContext): print(f"[{datetime.datetime.now()}] {ctx.author} invoked /{ctx.invoke_target}") async def handle_error(self, error: Exception, ctx: BaseContext): await ctx.send(f"Moderation error: {error}", ephemeral=True) @slash_command(name="kick", description="Kick a member") async def kick(self, ctx: SlashContext): await ctx.send("Member kicked.") ``` ### Loading Extensions (`main.py`) ```python from interactions import Client, Intents bot = Client(intents=Intents.DEFAULT) bot.load_extension("cogs.moderation") # load # bot.reload_extension("cogs.moderation") # hot-reload # bot.unload_extension("cogs.moderation") # remove bot.start("TOKEN") ``` ``` -------------------------------- ### Asynchronous Extension Initialization with `async_start` Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/20 Extensions.md Implement `async_start` for asynchronous initialization logic that runs once when the bot starts. ```python class MyExtension(Extension): async def async_start(self): # do some initialization here pass ``` -------------------------------- ### UserSelectMenu Example Source: https://context7.com/interactions-py/interactions.py/llms.txt Demonstrates how to create and use a UserSelectMenu for selecting users. ```APIDOC ## UserSelectMenu ### Description Allows users to pick one or more users from a user selection menu. ### Method `UserSelectMenu()` ### Parameters - `custom_id` (str) - Unique identifier for the menu. ### Usage Example ```python from interactions import UserSelectMenu await ctx.send("Pick someone:", components=UserSelectMenu(custom_id="user_pick")) ``` ### Callback Example ```python from interactions import ComponentContext @component_callback("user_pick") async def user_picked(ctx: ComponentContext): await ctx.send(f"You picked: {ctx.values[0]}", ephemeral=True) ``` ``` -------------------------------- ### Asynchronous Extension Initialization with `Startup` Event Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/20 Extensions.md Use the `Startup` event decorator to run asynchronous initialization logic when the bot starts. ```python from interactions.api.events import Startup class MyExtension(Extension): @event(Startup) async def startup(self): # do some initialization here pass ``` -------------------------------- ### Install discord-py-interactions (Windows) Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/01 Getting Started.md Install the interactions.py library using pip on Windows. ```shell py -3 -m pip install discord-py-interactions --upgrade ``` -------------------------------- ### v4: Creating tasks and loading extensions before bot start Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/98 Migration from 4.X.md In v4, the library would create an asyncio loop if none was detected and store it in `bot._loop`. This allowed tasks to be created and extensions to be loaded before the bot started. ```python import interactions # if there's no loop detected, v4 would create the loop for you at this point # it also stores the loop in bot._loop bot = interactions.Client(...) bot._loop.create_task(some_func()) bot.load("an_ext_that_uses_the_event_loop") bot.start() ``` -------------------------------- ### StringSelectMenu Example Source: https://context7.com/interactions-py/interactions.py/llms.txt Demonstrates how to create and use a StringSelectMenu for user selection. ```APIDOC ## StringSelectMenu ### Description Allows users to pick one or more options from a dropdown menu. ### Method `StringSelectMenu()` ### Parameters - `"šŸ• Pizza"`, `"šŸ Pasta"`, `"šŸ” Burger"`, `"šŸ„— Salad"` (str) - Options for the select menu. - `placeholder` (str) - Optional placeholder text for the menu. - `custom_id` (str) - Unique identifier for the menu. - `min_values` (int) - Minimum number of values the user must select. - `max_values` (int) - Maximum number of values the user can select. ### Usage Example ```python from interactions import StringSelectMenu menu = StringSelectMenu( "šŸ• Pizza", "šŸ Pasta", "šŸ” Burger", "šŸ„— Salad", placeholder="Choose your meal", custom_id="food_select", min_values=1, max_values=2, ) await ctx.send("Pick your meal:", components=menu) ``` ### Callback Example ```python from interactions import ComponentContext @component_callback("food_select") async def food_selected(ctx: ComponentContext): choices = ", ".join(ctx.values) await ctx.send(f"You chose: **{choices}**", ephemeral=True) ``` ``` -------------------------------- ### Install discord-py-interactions (Linux) Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/01 Getting Started.md Install the interactions.py library using pip on Linux. ```shell python3 -m pip install discord-py-interactions --upgrade ``` -------------------------------- ### Install discord-py-interactions with development dependencies Source: https://github.com/interactions-py/interactions.py/blob/stable/CONTRIBUTING.rst Install the library with development dependencies using pip. This is recommended for contributing to the project. ```bash pip install -U discord-py-interactions[dev] ``` -------------------------------- ### Voice Playback and Recording Setup Source: https://context7.com/interactions-py/interactions.py/llms.txt Provides basic imports for voice channel functionalities like playing audio and recording. Further implementation details for playback and recording would follow. ```python import asyncio from interactions import slash_command, slash_option, SlashContext, OptionType, File from interactions.api.voice.audio import AudioVolume ``` -------------------------------- ### Slash Command and Context Menu Examples Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/90 Example.md This extension showcases how to define slash commands with options and context menus using interactions.py. It includes examples of command error handling and pre-run hooks. ```python from interactions import slash_command, slash_option, SlashContext, context_menu, CommandType, Button, ActionRow, ButtonStyle, Extension class CommandsExampleSkin(Extension): @slash_command("command", description="This is a test", scopes=701347683591389185) @slash_option("another", "str option", 3, required=True) @slash_option("option", "int option", 4, required=True) async def command(self, ctx: SlashContext, **kwargs): await ctx.send(str(ctx.resolved)) await ctx.send(f"Test: {kwargs}", components=[ActionRow(Button(1, "Test"))]) print(ctx.resolved) @command.error async def command_error(self, e, *args, **kwargs): print(f"Command hit error with {args=}, {kwargs=}") @command.pre_run async def command_pre_run(self, context, *args, **kwargs): print("I ran before the command did!") @context_menu(name="user menu", context_type=CommandType.USER, scopes=701347683591389185) async def user_context(self, ctx): await ctx.send("Context menu:: user") def setup(bot): CommandsExampleSkin(bot) ``` -------------------------------- ### Tasks Example Source: https://context7.com/interactions-py/interactions.py/llms.txt Demonstrates how to schedule background tasks using various triggers. ```APIDOC ## Tasks — Background Processes ### Description `Task` runs async functions on a schedule using `IntervalTrigger`, `DateTrigger`, `TimeTrigger`, or `OrTrigger`. Tasks can be started from the `Startup` event. ### Triggers - `IntervalTrigger(minutes=30)`: Runs at a fixed interval. - `TimeTrigger(hour=0, minute=0)`: Runs at a specific time each day. - `DateTrigger()`: Runs at a specific date and time. - `OrTrigger()`: Combines multiple triggers. ### Example: Interval Trigger ```python from interactions import Task, IntervalTrigger, Client, Intents, Activity bot = Client(intents=Intents.DEFAULT) @Task.create(IntervalTrigger(minutes=30)) async def status_update(): await bot.change_presence(activity=Activity(name="with Python!")) ``` ### Example: Time Trigger ```python from interactions import Task, TimeTrigger, Client, Intents bot = Client(intents=Intents.DEFAULT) @Task.create(TimeTrigger(hour=0, minute=0)) async def daily_reset(): print("Daily counters reset.") ``` ``` -------------------------------- ### Start Recording to Output Directory Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/23 Voice.md To save recordings directly to disk instead of keeping them in memory, specify an `output_dir` in the `start_recording` method. The library will not create the directory or manage files. ```python await voice_state.start_recording(output_dir="folder_name") ``` -------------------------------- ### Button Component Examples Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/90 Example.md This extension demonstrates how to create and send messages with buttons using interactions.py. It includes examples for single buttons, multiple buttons in a row, and buttons organized within ActionRows. ```python from interactions import Button, ActionRow, ButtonStyle, Extension from interactions.ext.prefixed_commands import prefixed_command class ButtonExampleSkin(Extension): @prefixed_command() async def blurple_button(self, ctx): await ctx.send("hello there", components=Button(ButtonStyle.BLURPLE, "A blurple button")) @prefixed_command() async def multiple_buttons(self, ctx): await ctx.send( "2 buttons in a row", components=[Button(ButtonStyle.BLURPLE, "A blurple button"), Button(ButtonStyle.RED, "A red button")], ) @prefixed_command() async def action_rows(self, ctx): await ctx.send( "2 buttons in 2 rows, using nested lists", components=[[Button(ButtonStyle.BLURPLE, "A blurple button")], [Button(ButtonStyle.RED, "A red button")]], ) @prefixed_command() async def action_rows_more(self, ctx): await ctx.send( "2 buttons in 2 rows, using explicit action_rows lists", components=[ ActionRow(Button(ButtonStyle.BLURPLE, "A blurple button")), ActionRow(Button(ButtonStyle.RED, "A red button")), ], ) def setup(bot): ButtonExampleSkin(bot) ``` -------------------------------- ### Bot Structure Using Extensions Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/20 Extensions.md This example demonstrates how to structure a bot using extensions. The main file handles core logic and extension loading, while a separate file contains the commands and listeners. ```python # File: `main.py` from interactions import Client, Intents, listen from interactions.api.events import Component, GuildJoin, MessageCreate, Startup bot = Client(intents=Intents.DEFAULT | Intents.MESSAGE_CONTENT) @listen(Startup) async def on_startup(): print(f"Ready - this bot is owned by {bot.owner}") @listen(GuildJoin) async def on_guild_join(event: GuildJoin): print(f"Guild joined : {event.guild.name}") @listen(MessageCreate) async def on_message_create(event: MessageCreate): print(f"message received: {event.message}") @listen() async def on_component(event: Component): ctx = event.ctx await ctx.edit_origin(content="test") bot.load_extension("test_components") bot.start("token") ``` ```python # File: `test_components.py` from interactions import ActionRow, Button, ButtonStyle, Extension, slash_command class ButtonExampleSkin(Extension): @slash_command() async def multiple_buttons(self, ctx): await ctx.send( "2 buttons in a row", components=[ Button(style=ButtonStyle.BLURPLE, label="A blurple button"), Button(style=ButtonStyle.RED, label="A red button"), ], ) @slash_command() async def action_rows(self, ctx): await ctx.send( "2 buttons in 2 rows, using nested lists", components=[ [Button(style=ButtonStyle.BLURPLE, label="A blurple button")], [Button(style=ButtonStyle.RED, label="A red button")], ], ) @slash_command() async def action_rows_more(self, ctx): await ctx.send( "2 buttons in 2 rows, using explicit action_rows lists", components=[ ActionRow(Button(style=ButtonStyle.BLURPLE, label="A blurple button")), ActionRow(Button(style=ButtonStyle.RED, label="A red button")), ], ) ``` -------------------------------- ### Modal Example Source: https://context7.com/interactions-py/interactions.py/llms.txt Demonstrates how to create and use Modals with ShortText and ParagraphText fields. ```APIDOC ## Modals ### Description Modals are popup forms supporting short text and paragraph text fields. They can be responded to via `bot.wait_for_modal()` or the persistent `@modal_callback()`. ### Method `Modal()` ### Parameters - `ShortText()`: For short text input. - `label` (str) - Label for the text field. - `custom_id` (str) - Unique identifier for the text field. - `placeholder` (str) - Optional placeholder text. - `max_length` (int) - Maximum length of the input. - `ParagraphText()`: For longer text input. - `label` (str) - Label for the text field. - `custom_id` (str) - Unique identifier for the text field. - `placeholder` (str) - Optional placeholder text. - `min_length` (int) - Minimum length of the input. - `required` (bool) - Whether the field is required. - `title` (str) - The title of the modal. - `custom_id` (str) - Unique identifier for the modal. ### Usage Example ```python from interactions import Modal, ShortText, ParagraphText, SlashContext modal = Modal( ShortText(label="Subject", custom_id="subject", placeholder="Brief summary", max_length=100), ParagraphText( label="Details", custom_id="details", placeholder="Tell us more...", min_length=20, required=False ), title="Submit Feedback", custom_id="feedback_modal", ) await ctx.send_modal(modal) ``` ### Callback Example ```python from interactions import ModalContext @modal_callback("feedback_modal") async def on_feedback(ctx: ModalContext, subject: str, details: str): await ctx.send( f"**Feedback received!**\n**Subject:** {subject}\n**Details:** {details or 'N/A'}", ephemeral=True ) ``` ### `wait_for_modal` Example ```python from interactions import Modal, ShortText, SlashContext, ModalContext modal = Modal( ShortText(label="Your name", custom_id="name"), title="Who are you?", custom_id="name_modal", ) await ctx.send_modal(modal) modal_ctx: ModalContext = await ctx.bot.wait_for_modal(modal, timeout=120) await modal_ctx.send(f"Hello, **{modal_ctx.responses['name']}**!", ephemeral=True) ``` ``` -------------------------------- ### Basic Extension Structure Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/20 Extensions.md A minimal extension must inherit from the `Extension` class. No `__init__` or `setup` function is strictly required for basic functionality. ```python from interactions import Extension class MyExtension(Extension): pass ``` -------------------------------- ### Enable Jurigged Extension Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/22 Live Patching.md Load the jurigged extension to enable live patching. This is the basic setup required. ```python bot.load_extension("interactions.ext.jurigged") ``` -------------------------------- ### User Cooldown Example Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/API Reference/API Reference/models/Internal/cooldowns.md This example demonstrates how to apply a cooldown to a slash command, limiting its usage per user. The command can be used once every 10 seconds by each individual user. ```python from interactions import slash_command, cooldown, Buckets @slash_command(name='cmd') @cooldown(Buckets.user, 1, 10) # (1)! async def some_command(ctx): ... ``` -------------------------------- ### Monolithic Bot Structure Without Extensions Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/20 Extensions.md This example shows a complete bot with all commands and listeners in a single file. It includes startup, guild join, message creation, component interaction, and slash commands. ```python from interactions import ActionRow, Button, ButtonStyle, Client, Intents, listen, slash_command from interactions.api.events import Component, GuildJoin, MessageCreate, Startup bot = Client(intents=Intents.DEFAULT | Intents.MESSAGE_CONTENT) @listen(Startup) async def on_startup(): print(f"Ready - this bot is owned by {bot.owner}") @listen(GuildJoin) async def on_guild_join(event: GuildJoin): print(f"Guild joined : {event.guild.name}") @listen(MessageCreate) async def on_message_create(event: MessageCreate): print(f"message received: {event.message}") @listen() async def on_component(event: Component): ctx = event.ctx await ctx.edit_origin(content="test") @slash_command() async def multiple_buttons(ctx): await ctx.send( "2 buttons in a row", components=[ Button(style=ButtonStyle.BLURPLE, label="A blurple button"), Button(style=ButtonStyle.RED, label="A red button"), ], ) @slash_command() async def action_rows(ctx): await ctx.send( "2 buttons in 2 rows, using nested lists", components=[ [Button(style=ButtonStyle.BLURPLE, label="A blurple button")], [Button(style=ButtonStyle.RED, label="A red button")], ], ) @slash_command() async def action_rows_more(ctx): await ctx.send( "2 buttons in 2 rows, using explicit action_rows lists", components=[ ActionRow(Button(style=ButtonStyle.BLURPLE, label="A blurple button")), ActionRow(Button(style=ButtonStyle.RED, label="A red button")), ], ) bot.start("token") ``` -------------------------------- ### Loading an Extension Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/20 Extensions.md Load an extension by calling `bot.load_extension()` with the import path of the extension file (without the `.py` extension) before starting the bot. ```python from interactions import Client bot = Client(...) bot.load_extension("extension") bot.start("token") ``` -------------------------------- ### Prefixed Commands Setup Source: https://context7.com/interactions-py/interactions.py/llms.txt Sets up the prefixed commands extension for the bot, allowing commands to be triggered by a message prefix. Specify the default prefix or a list of prefixes. ```python from interactions import Client, Intents from interactions.ext import prefixed_commands from interactions.ext.prefixed_commands import prefixed_command, PrefixedContext bot = Client(intents=Intents.DEFAULT | Intents.GUILD_MESSAGES | Intents.MESSAGE_CONTENT) prefixed_commands.setup(bot, default_prefix="!") # or a list: ["!", "?"] @prefixed_command(name="hello") async def hello(ctx: PrefixedContext): await ctx.reply(f"Hello, {ctx.author.display_name}!") @prefixed_command(name="add") async def add(ctx: PrefixedContext, a: int, b: int): await ctx.reply(f"{a} + {b} = {a + b}") @prefixed_command(name="greet") async def greet(ctx: PrefixedContext): await ctx.reply("Base command.") @greet.subcommand() async def warmly(ctx: PrefixedContext): await ctx.reply("Hello there, wonderful person!") bot.start("TOKEN") ``` -------------------------------- ### Pass Arguments to Extension Initialization Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/20 Extensions.md When loading an extension, you can pass additional keyword arguments to the `load_extension` method. These arguments will be passed to the extension's `__init__` method or its `setup` function if one is defined. ```python from interactions import Extension, Client class MyExtension(Extension): def __init__(self, bot: Client, some_arg: int = 0): ... bot.load_extension("extension", some_arg=5) ``` ```python from interactions import Extension, Client class MyExtension(Extension): ... def setup(bot: Client, some_arg: int = 0): MyExtension(bot, some_arg) ``` -------------------------------- ### Start Recording with Custom Encoding Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/23 Voice.md Customize the audio encoding for recordings by passing the desired encoding format to the `start_recording` method. Refer to the Recorder documentation for a list of available encodings. ```python await voice_state.start_recording(encoding="wav") ``` -------------------------------- ### v5: Using asyncio.run and bot.astart for loop management Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/98 Migration from 4.X.md In v5, asyncio encourages a single loop managed by asyncio itself. Use `asyncio.run(main())` to create the loop and `bot.astart()` within an async function to start the bot, allowing `asyncio.create_task` to be used safely after the loop is running. ```python import asyncio import interactions # no bot._loop, loop also does not exist yet bot = interactions.Client(...) async def main(): # loop now exists, woo! asyncio.create_task(some_func()) bot.load_extension("an_ext_that_uses_the_event_loop") await bot.astart() # a function in asyncio that creates the loop for you and runs # the function within asyncio.run(main()) ``` -------------------------------- ### Play Audio from URL Source: https://context7.com/interactions-py/interactions.py/llms.txt Plays audio from a given URL in the user's voice channel. Requires FFmpeg to be installed. ```python from interactions import slash_command, SlashContext, OptionType from interactions.ext.audio import AudioVolume @slash_command("play", description="Play audio in your voice channel") @slash_option("url", "Audio URL or search query", required=True, opt_type=OptionType.STRING) async def play(ctx: SlashContext, url: str): if not ctx.voice_state: await ctx.author.voice.channel.connect() audio = await AudioVolume(url) await ctx.send(f"ā–¶ Now playing: **{url}**") await ctx.voice_state.play(audio) ``` -------------------------------- ### Setup Prefixed Commands Extension Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/99 2.x Migration_NAFF.md Load the prefixed commands extension for interactions.py. Guild messages are included in default intents. Guild message content is required if the prefix is not bot mention. ```python from interactions import Client, Intents from interactions.ext import prefixed_commands # guild messages are included in the default intents ipy uses # if you wish for the prefix to be anything but mentioning the bot, # guild message content will also be required client = Client(..., intents=Intents.GUILD_MESSAGES | ...) prefixed_commands.setup(client) ``` -------------------------------- ### Basic interactions.py Bot Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/01 Getting Started.md A minimal Python script to initialize a Discord bot client, listen for ready and message events, and start the bot. ```python from interactions import Client, Intents, listen bot = Client(intents=Intents.DEFAULT) # intents are what events we want to receive from discord, `DEFAULT` is usually fine @listen() # this decorator tells snek that it needs to listen for the corresponding event, and run this coroutine async def on_ready(): # This event is called when the bot is ready to respond to commands print("Ready") print(f"This bot is owned by {bot.owner}") @listen() async def on_message_create(event): # This event is called when a message is sent in a channel the bot can see print(f"message received: {event.message.jump_url}") bot.start("Put your token here") ``` -------------------------------- ### Create a Custom Converter Class Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/08 Converters.md Subclass `interactions.Converter` and implement the `convert` method to define custom logic for argument transformation. This example converts a string to its uppercase equivalent. ```python from interactions import Converter class UpperConverter(Converter): async def convert(ctx: BaseContext, argument: str): return argument.upper() ``` -------------------------------- ### Setup Prefixed Commands Extension Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/26 Prefixed Commands.md Integrate the prefixed commands extension into your interactions.py bot. Ensure guild message intents are enabled, and consider enabling message content intent if using custom prefixes. ```python from interactions import Client, Intents from interactions.ext import prefixed_commands # guild messages are included in the default intents ipy uses # if you wish for the prefix to be anything but mentioning the bot, # guild message content will also be required client = Client(..., intents=Intents.GUILD_MESSAGES | ...) prefixed_commands.setup(client) ``` -------------------------------- ### Implement a Custom Command Check Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/03 Creating Commands.md Define a custom asynchronous function to act as a check, allowing for flexible access control logic. This example checks if the author's username starts with 'a'. ```python from interactions import check async def my_check(ctx: BaseContext): return ctx.author.username.startswith("a") @slash_command(name="my_command") @check(my_check) async def command(ctx: SlashContext): await ctx.send("Your username starts with an 'a'!", ephemeral=True) ``` -------------------------------- ### Listen to Startup Event (No Arguments) Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/10 Events.md Handle events that do not pass any specific information by simply not defining any parameters for the listener function. The library will pass an empty object if no arguments are expected. ```python from interactions.api.events import Startup @listen(Startup) async def startup_func(): ... ``` -------------------------------- ### Define and Load an Extension Source: https://context7.com/interactions-py/interactions.py/llms.txt Shows how to create an `Extension` subclass for organizing commands and listeners, including custom checks, pre-run hooks, and error handling. It also demonstrates loading the extension in the main bot file. ```python # cogs/moderation.py import datetime from interactions import Extension, slash_command, SlashContext, BaseContext, Client class Moderation(Extension): def __init__(self, bot: Client): self.add_ext_check(self.guild_only_check) self.add_extension_prerun(self.log_invocation) self.set_extension_error(self.handle_error) self.add_ext_auto_defer(enabled=True, ephemeral=True, time_until_defer=0.5) async def guild_only_check(self, ctx: BaseContext) -> bool: return ctx.guild is not None async def log_invocation(self, ctx: BaseContext): print(f"[{datetime.datetime.now()}] {ctx.author} invoked /{ctx.invoke_target}") async def handle_error(self, error: Exception, ctx: BaseContext): await ctx.send(f"Moderation error: {error}", ephemeral=True) @slash_command(name="kick", description="Kick a member") async def kick(self, ctx: SlashContext): await ctx.send("Member kicked.") # main.py from interactions import Client, Intents bot = Client(intents=Intents.DEFAULT) bot.load_extension("cogs.moderation") # load # bot.reload_extension("cogs.moderation") # hot-reload # bot.unload_extension("cogs.moderation") # remove bot.start("TOKEN") ``` -------------------------------- ### Asynchronous Initialization with `asyncio.create_task` Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/20 Extensions.md Use `asyncio.create_task` within `__init__` to run asynchronous initialization logic every time the extension is loaded. This requires an active event loop, typically provided by `bot.start()` or `bot.astart()`. ```python import asyncio class MyExtension(Extension): def __init__(self, bot): asyncio.create_task(self.async_init()) async def async_init(self): # do some initialization here pass ``` -------------------------------- ### Synchronous Extension Initialization Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/20 Extensions.md Use the `__init__` method for synchronous initialization logic when loading an extension. ```python class MyExtension(Extension): def __init__(self, bot): # do some initialization here pass ``` -------------------------------- ### Instantiate and run a basic bot with debug logging Source: https://github.com/interactions-py/interactions.py/blob/stable/CONTRIBUTING.rst Instantiate a basic bot client with a token and enable debug logging. Logging set to True automatically sets the level to DEBUG, but other levels can be specified. ```python import interactions bot = interactions.Client(token="...", logging=True) # ``True`` sets logging to DEBUG automatically but you can also set another logging level bot.start() ``` -------------------------------- ### Task Scheduling with Triggers Source: https://context7.com/interactions-py/interactions.py/llms.txt Schedules tasks to run at specific times or intervals using TimeTrigger and DateTrigger. Ensure the bot is started with the necessary tasks. ```python from interactions import Task, OrTrigger, TimeTrigger, DateTrigger from datetime import datetime # Twice a day @Task.create(OrTrigger(TimeTrigger(hour=9, minute=0), TimeTrigger(hour=17, minute=0))) async def twice_daily(): print("Morning or afternoon check-in.") # One-shot: specific datetime @Task.create(DateTrigger(datetime(2025, 12, 31, 23, 59))) async def new_year(): print("Happy New Year!") @listen(Startup) async def on_ready(): status_update.start() daily_reset.start() twice_daily.start() new_year.start() ``` -------------------------------- ### Registering a Prefixed Help Command Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/26 Prefixed Commands.md Implement a help command using PrefixedHelpCommand for ease of use. Various options are available for customization. ```python from interactions.ext.prefixed_command.help import PrefixedHelpCommand # There are a variety of options - adjust them to your liking! help_cmd = PrefixedHelpCommand(bot, ...) help_cmd.register() ``` -------------------------------- ### Sentry Error Tracking Integration Source: https://context7.com/interactions-py/interactions.py/llms.txt Integrates Sentry.io for production error monitoring. Also shows a basic Discord channel logging setup for development. ```python from interactions import Client, Intents from interactions.api.events import Error bot = Client(intents=Intents.DEFAULT, send_command_tracebacks=False) # Built-in Sentry integration (recommended for production) bot.load_extension("interactions.ext.sentry", dsn="https://...@o9253.sentry.io/1048576") # Simple Discord channel logging (dev/debugging only) @bot.listen() async def on_error(error: Error): channel = await bot.fetch_channel(123456789012345678) await channel.send(f"```\n{error.source}\n{error.error}\n```") bot.start("TOKEN") ``` -------------------------------- ### Restrict Channel Type for Command Option Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/03 Creating Commands.md Use `channel_types` to limit the selectable channels for a `OptionType.CHANNEL` option. This example restricts it to guild text channels. ```python from interactions import ChannelType, GuildText, OptionType, SlashContext, slash_command, slash_option @slash_command(name="my_command") @slash_option( name="channel_option", description="Channel Option", required=True, opt_type=OptionType.CHANNEL, channel_types=[ChannelType.GUILD_TEXT], ) async def my_command_function(ctx: SlashContext, channel_option: GuildText): await channel_option.send("This is a text channel in a guild") await ctx.send("...") ``` -------------------------------- ### Create and Activate Virtual Environment (Linux) Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/01 Getting Started.md Use this command to create a virtual environment for your bot project on Linux systems. ```shell cd "[your bots directory]" python3 -m venv venv source venv/bin/activate ``` -------------------------------- ### Create and Activate Virtual Environment (Windows) Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/01 Getting Started.md Use this command to create a virtual environment for your bot project on Windows systems. ```shell cd "[your bots directory]" py -3 -m venv venv venv/Scripts/activate ``` -------------------------------- ### Create and Handle Quick Input Modal with wait_for_modal Source: https://context7.com/interactions-py/interactions.py/llms.txt Demonstrates using `bot.wait_for_modal()` to handle a simple modal for text input, capturing the response after a timeout. ```python from interactions import ( Modal, ShortText, ParagraphText, ModalContext, SlashContext, slash_command, modal_callback ) # Alternative: wait_for_modal (same-function flow) @slash_command(name="quick_input", description="Quick text input") async def quick_input(ctx: SlashContext): modal = Modal( ShortText(label="Your name", custom_id="name"), title="Who are you?", custom_id="name_modal", ) await ctx.send_modal(modal) modal_ctx: ModalContext = await ctx.bot.wait_for_modal(modal, timeout=120) await modal_ctx.send(f"Hello, **{modal_ctx.responses['name']}**!", ephemeral=True) ``` -------------------------------- ### Play Audio in Voice Channel Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/API Reference/API Reference/models/Internal/active_voice_state.md Connects the bot to the author's voice channel if not already connected, then plays the specified song. Refer to the Voice Support Guide for more details on audio playback. ```python from interactions import slash_command, slash_option, OptionType, SlashContext from interactions.api.voice.audio import AudioVolume @slash_command("play") @slash_option("song", "The song to play", OptionType.STRING, required=True) async def test_cmd(ctx: SlashContext, song: str): await ctx.defer() if not ctx.voice_state: await ctx.author.voice.channel.connect() # (1)! await ctx.send(f"Playing {song}") await ctx.voice_state.play(AudioVolume(song)) # (2)! ``` -------------------------------- ### Record Audio in Voice Channel Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/23 Voice.md This command records audio from a voice channel for a specified duration. It connects to the author's voice channel, starts recording, waits for 10 seconds, stops recording, and sends the recorded files. ```python import asyncio import interactions @interactions.slash_command("record", "record some audio") async def record(ctx: interactions.SlashContext): voice_state = await ctx.author.voice.channel.connect() # Start recording await voice_state.start_recording() await asyncio.sleep(10) await voice_state.stop_recording() await ctx.send(files=[interactions.File(file, file_name="user_id.mp3") for user_id, file in voice_state.recorder.output.items()]) ``` -------------------------------- ### Loading Extensions from a Flat Folder Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/20 Extensions.md Use `pkgutil.iter_modules` to load all extensions from a flat folder structure. Ensure the `prefix` argument correctly matches your folder name to form valid import paths. ```python import pkgutil # replace "exts" with your folder name extension_names = [m.name for m in pkgutil.iter_modules(["exts"], prefix="exts.")] for extension in extension_names: bot.load_extension(extension) ``` -------------------------------- ### Create and Handle User Select Menu Source: https://context7.com/interactions-py/interactions.py/llms.txt Defines a slash command to prompt users to pick another user from a select menu, and a callback to handle the user selection. ```python from interactions import ( StringSelectMenu, UserSelectMenu, ComponentContext, SlashContext, slash_command, component_callback ) @slash_command(name="mention_user", description="Pick a user to mention") async def mention_user(ctx: SlashContext): await ctx.send("Pick someone:", components=UserSelectMenu(custom_id="user_pick")) @component_callback("user_pick") async def user_picked(ctx: ComponentContext): await ctx.send(f"You picked: {ctx.values[0]}", ephemeral=True) ``` -------------------------------- ### Custom Extension Teardown Function Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/20 Extensions.md Implement a `teardown` function outside of an `Extension` subclass to perform custom cleanup logic when an extension is unloaded. This function takes no arguments and is typically used for releasing resources or undoing setup actions. ```python from interactions import Extension class MyExtension(Extension): ... def teardown(): # insert logic here pass ``` -------------------------------- ### Setting up Hybrid Commands Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/03 Creating Commands.md To enable hybrid commands, first set up the `prefixed_commands` extension, then set up the `hybrid_commands` extension. This allows slash commands to also be triggered by prefixed messages. ```python import interactions from interactions.ext import prefixed_commands as prefixed from interactions.ext import hybrid_commands as hybrid bot = interactions.Client(...) # may want to enable the message content intent prefixed.setup(bot) # normal step for prefixed commands hybrid.setup(bot) # note its usage AFTER prefixed commands have been set up ``` -------------------------------- ### Create Basic Slash Commands Source: https://context7.com/interactions-py/interactions.py/llms.txt Register application commands using the @slash_command decorator. Remember that commands must be responded to within 3 seconds, or use ctx.defer() for longer operations. ```python import asyncio from interactions import slash_command, SlashContext @slash_command(name="ping", description="Check bot latency") async def ping(ctx: SlashContext): await ctx.send("Pong! šŸ“") @slash_command(name="slow_command", description="A command that takes time") async def slow_command(ctx: SlashContext): await ctx.defer() # extends deadline to 15 minutes await asyncio.sleep(5) await ctx.send("Done!") # Guild-only (non-global) command for testing @slash_command(name="secret", description="Guild only", scopes=[870046872864165888]) async def secret(ctx: SlashContext): await ctx.send("Only visible in this server!", ephemeral=True) ``` -------------------------------- ### Global Error Listener Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/03 Creating Commands.md Override the default error listener by defining a global listener for `CommandError`. This listener will catch errors from all commands, including context menus and prefixed commands. Ensure `disable_default_listeners=True` is set to prevent duplicate error handling. This example logs the error and responds to the interaction if it hasn't been responded to yet. ```python import traceback from interactions.api.events import CommandError from interactions import listen @listen(CommandError, disable_default_listeners=True) async def on_command_error(event: CommandError): traceback.print_exception(event.error) if not event.ctx.responded: await event.ctx.send("Something went wrong.") ``` -------------------------------- ### Create a Basic Modal Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/06 Modals.md Use `ctx.send_modal()` to send a modal to the user. Modals can contain short and paragraph text inputs, each with a unique `custom_id`. ```python from interactions import Modal, ParagraphText, ShortText, SlashContext, slash_command @slash_command(name="my_modal_command", description="Playing with Modals") async def my_command_function(ctx: SlashContext): my_modal = Modal( ShortText(label="Short Input Text", custom_id="short_text"), ParagraphText(label="Long Input Text", custom_id="long_text"), title="My Modal", ) await ctx.send_modal(modal=my_modal) ``` -------------------------------- ### Load Sentry Extension for Error Tracking Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/25 Error Tracking.md Integrate Sentry.io for robust error tracking by loading the `interactions.ext.sentry` extension early in your bot's startup. This ensures initialization errors are also captured. ```python bot.load_extension('interactions.ext.sentry', dsn=SENTRY_DSN) ``` -------------------------------- ### Create a Bot with AutoShardedClient Source: https://context7.com/interactions-py/interactions.py/llms.txt Use AutoShardedClient as a drop-in replacement for Client for automatic sharding, recommended for bots in 2500+ guilds. Replace 'YOUR_BOT_TOKEN' with your actual bot token. ```python from interactions import AutoShardedClient, listen class Bot(AutoShardedClient): @listen() async def on_ready(self): print(f"Sharded bot ready — owned by {self.owner}") @listen() async def on_message_create(self, event): print(f"Message: {event.message.content}") bot = Bot(intents=Intents.DEFAULT) bot.start("YOUR_BOT_TOKEN") ``` -------------------------------- ### Create a Minimal Bot with Client Source: https://context7.com/interactions-py/interactions.py/llms.txt Create a minimal Discord bot using the Client class. Intents control received gateway events, and debug_scope can be used for development guild command scoping. Ensure to replace 'YOUR_BOT_TOKEN' with your actual bot token. ```python from interactions import Client, Intents, listen from interactions.api.events import Startup bot = Client( intents=Intents.DEFAULT, debug_scope=870046872864165888, # guild ID for test commands send_command_tracebacks=False, # disable traceback responses in production ) @listen(Startup) async def on_startup(): print(f"Ready — owned by {bot.owner}") bot.start("YOUR_BOT_TOKEN") ``` -------------------------------- ### Context Menus Source: https://context7.com/interactions-py/interactions.py/llms.txt Create context menu commands for messages and users. ```APIDOC ## Context Menus Context menus appear when right-clicking a message or user in Discord under the "Apps" submenu. Names can contain spaces, uppercase, and special symbols. ```python from interactions import ContextMenuContext, Message, Member from interactions import message_context_menu, user_context_menu @message_context_menu(name="Quote Message") async def quote_message(ctx: ContextMenuContext): message: Message = ctx.target await ctx.send(f'> {message.content}\n— {message.author.mention}') @user_context_menu(name="Get Avatar") async def get_avatar(ctx: ContextMenuContext): member: Member = ctx.target await ctx.send(f"**{member.display_name}'s avatar:**\n{member.avatar.url}") ``` ``` -------------------------------- ### Add Extension-Wide Pre- and Post-Run Events Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/20 Extensions.md Register functions to run before (`add_extension_prerun`) and after (`add_extension_postrun`) any command in an extension is invoked. These functions receive the context and can be used for logging, timing, or other pre/post-command operations. ```python import datetime from interactions import Extension, Client, BaseContext, slash_command class MyExtension(Extension): def __init__(self, bot: Client): self.add_extension_prerun(self.pre_run) self.add_extension_postrun(self.post_run) async def pre_run(ctx: BaseContext): print(f"Command started at: {datetime.datetime.now()}") async def post_run(ctx: BaseContext): print(f"Command done at: {datetime.datetime.now()}") @slash_command(...) async def my_command(...): # pre and post run will be ran before/after this command ... ``` -------------------------------- ### Modal Creation: v4 vs v5 Source: https://github.com/interactions-py/interactions.py/blob/stable/docs/src/Guides/98 Migration from 4.X.md Modal creation syntax has changed. In v5, `ActionRow` can be instantiated directly, and `Modal` accepts components as `*args`. ```python import interactions # in v4: components = [interactions.TextInput(...), interactions.TextInput(...)] modal = interactions.Modal( title="Application Form", custom_id="mod_app_form", components=components, ) # in v5: components = [interactions.InputText(...), interactions.InputText(...)] modal = interactions.Modal( *components, title="Application Form", custom_id="mod_app_form", ) ```