Search code examples
pythondiscorddiscord.pypycord

Want to create new text channel with discord bot button


I want to create a discord bot that is able to create a new private text channel between the person who clicked the button and our mods of the server. I can't figure out how to get the button to recognize the interaction.

Currently, the code below gets returns this in the terminal when I click the button:

> await interaction.guild.create_text_channel("Bot-made channel", category="brendan")
> AttributeError: 'Button' object has no attribute 'guild'

with "interaction.guild" underlined
import discord
from discord.ui import Button, View
from discord.ext import commands
from discord import Intents
from discord import Permissions
from discord.utils import get

guild = serverID
vanguard = roleID

bot = commands.Bot(command_prefix='>', intents=Intents.all())

class MyView(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.value = None

    @discord.ui.button(label="Create new private channel", style=discord.ButtonStyle.gray)
    async def menu1(self, button: discord.ui.Button, interaction: discord.Interaction):
        await interaction.guild.create_text_channel("Bot-made channel", category="general")

@bot.command()
async def menu(ctx):
    view = MyView()
    await ctx.reply(view=view)

bot.run('MyToken')

Solution

  • They swapped the item position and interaction position in the callbacks. So you can just swap their position.

    From

    async def menu1(self, button: discord.ui.Button, interaction: discord.Interaction):
        ...
    

    To

    async def menu1(self, interaction: discord.Interaction, button: discord.ui.Button):
        ...