Clicking on button in discord channel does not execute the code in on_button_click

Question:

The purpose of this code is to

  1. create the channel if it doesnt exist (this works) and write a welcome message in it (this works)
  2. when you type in !open_ticket it should create a button and display it along with a message (this works)
  3. click the button and it will create a new channel with the users name as part of it (this does not work)

the print does not display in the terminal so it tells me the code is never even executed.

Why?

import discord
from discord.ext import commands
from helperfunctions import create_default_message

token = 'my token'
my_guild = 'guild name'
channel_name = 'support-tx'

intents = discord.Intents.all()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents.all())

@bot.event
async def on_ready():
    for guild in bot.guilds:
        if guild.name == my_guild:
            break

    for channel in guild.channels:
        if channel.name == channel_name:
            print("support tickets channel already created")
            bCF = True #channel found
            break
        else:
            bCF = False
            
    #create support tickets channel if it doesnt exist
    if not bCF:
        await guild.create_text_channel(channel_name)
        #await sync_channel_permissions(guild,channel_name) #this isnt working
    
    #create the initial message if it doesnt exist
    await create_default_message(bot,channel_name)

    print(
        f"{bot.user} is connected to the following guild:n"
        f"{guild.name}(id: {guild.id})"
    )
    

    
@bot.event
async def on_message(message):
    if message.author == bot.user: #make sure bot doesnt read its own messages
        return
    #message_content = message.content.lower()
    await bot.process_commands(message)

@bot.command()
#using !open_ticket in the discord chat, this should create a button and type a message 
async def open_ticket(ctx):
    print("hello function executed")
    view = discord.ui.View()
    button = discord.ui.Button(label="Open Ticket", custom_id="openTicket")
    view.add_item(button)
    view.timeout = None  # set the view timeout to None
    bot.add_view(view) # register the view with the bot
    await ctx.send("Click the button to open a new support ticket.",view=view)


@bot.event
#clicking on the above button should run this code but it does not, the print line doesn't show in the console
async def on_button_click(interaction: discord.Interaction):
    print(f"Button clicked by {interaction.user}")
    if interaction.component.custom_id == "openTicket":
        print("Button clicked") # Add this line to check if the function is being executed
        user = interaction.user
        guild = interaction.guild
        channel_name = f"{user.name}'s Ticket"
        overwrites = {
            guild.default_role: discord.PermissionOverwrite(read_messages=False),
            user: discord.PermissionOverwrite(read_messages=True)
        }
        new_channel = await guild.create_text_channel(channel_name, overwrites=overwrites)
        await interaction.respond(content=f"Hello {user.mention}! Your ticket has been created in {new_channel.mention}.")        

bot.run(token)
Asked By: zoonosis

||

Answers:

There’s no event called on_button_click – that function is never getting called. We need to give the button a callback function for it actually to run when the button is pressed.

There’s a couple of ways we could do this. I’ve modified a section of your code so that we’re setting the button’s callback function equal to the on_button_click function you’ve defined. Can see the docs for that here. I removed the checking of the button pressed as well as that’s not necessary when we’re setting it to the callback of the button directly.

async def on_button_click(interaction: discord.Interaction):
    print(f"Button clicked by {interaction.user}")
    print("Button clicked") # Add this line to check if the function is being executed
    user = interaction.user
    guild = interaction.guild
    channel_name = f"{user.name}'s Ticket"
    overwrites = {
        guild.default_role: discord.PermissionOverwrite(read_messages=False),
        user: discord.PermissionOverwrite(read_messages=True)
    }
    new_channel = await guild.create_text_channel(channel_name, overwrites=overwrites)
    await interaction.respond(content=f"Hello {user.mention}! Your ticket has been created in {new_channel.mention}.") 


@bot.command()
async def open_ticket(ctx):
    print("hello function executed")
    view = discord.ui.View()
    button = discord.ui.Button(label="Open Ticket", custom_id="openTicket")
    button.callback = on_button_click
    view.add_item(button)
    view.timeout = None  # set the view timeout to None
    bot.add_view(view) # register the view with the bot
    await ctx.send("Click the button to open a new support ticket.",view=view)
Answered By: ESloman
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.