How to get a Nextcord Python Bot to react to button clicks?

Viewed 760

I'm trying to write a Discord Bot including a command for creating a poll like this: (The amount of options can be different)

/poll Is this bot working? <> Yes No Maybe

Then it already looks good:

(https://i.ibb.co/p3bmK5K/botbuttons.png)

However, I can't find out how to react on a button click (call the onpollbuttonclick(button) function.

Here's the relevant part of my code:

import nextcord
from nextcord.ext import commands

bot = commands.Bot(command_prefix="/")

@bot.command(name="poll")
async def poll(ctx, *, all):
    separator = all.find("<>")
    text = all[0:separator]
    newtext = ""
    for i in text:
        newtext += i
    options = all[separator+2:len(all)].split()
    pollbuttons = nextcord.ui.View()

    async def onpollbuttonclick(button):
        votestatus[button] += 1
        await ctx.send("Vote accepted!")
    
    votestatus = {}
    for i in options:
        pollbuttons.add_item(nextcord.ui.Button(style=nextcord.ButtonStyle.red, label=i))
        votestatus[i] = 0
    myembed = nextcord.Embed(title="Poll")
    myembed.add_field(name="\u200b", value=newtext, inline=False)
    await ctx.send(embed=myembed, view=pollbuttons)
    
bot.run("mytoken")
1 Answers

if you want to create a Button with a callback function try this. This is a little bit more work than with decorators, but you can change the labels on runtime. I hope it does the job because I didn't try it by myself.

import nextcord
from nextcord.ext import commands

bot = commands.Bot(command_prefix="/")


class Poll_Button(nextcord.ui.Button):
    def __init__(self,label): 
       self.super.init(custom_id="yourcustomid",
                       label=label,
                       style=nextcor.ButtonStlyle.red)

    async def callback(self,interaction:nextcord.Interaction):
        await interaction.send("Vote accepted")

class Poll_View(nextcord.ui.View):
    def __init__(self,options:List[str]):
        self.super.init()
        for option in options:
            self.add_item(Poll_Button(option))

@bot.command(name="poll")
async def poll(ctx,*,all):
    separator = all.find("<>")
    text = all[0:separator]
    newtext = ""
    for i in text:
        newtext += i
    options = all[separator+2:len(all)].split()
    
    myembed = nextcord.Embed(title="Poll")
    myembed.add_field(name="\u200b", value=newtext, inline=False)
    await ctx.send(embed=myembed, view=Poll_View(options)

bot.run("mytoken")

With a decorator, it looks something like this

@nextcor.ui.button(parameter):
async def funcname(button,interaction):
    await interaction.send("Vote accepted")
Related