如何让Nextcord Python Bot对按钮点击做出反应



我正在尝试编写一个Discord Bot,其中包括一个创建轮询的命令,如下所示:(选项的数量可能不同(

/poll这个机器人在工作吗<gt;是不是也许

然后它看起来已经很好了:

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

然而,我不知道如何对点击按钮做出反应(调用onpollbuttonclick(button)函数。

这是我代码的相关部分:

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")

如果您想创建一个带有回调函数的Button,请尝试此操作。这比使用装饰器要多一些,但您可以在运行时更改标签。我希望它能起作用,因为我不是自己尝试的。

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")

有了装饰器,它看起来像这个

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

最新更新