我希望這個命令可以同時在不同的地方作業。當我在一個頻道上運行它,而我的朋友在另一個頻道上運行它時,當我們中的一個人按下按鈕時,命令開始重復。我沒有點擊任何東西,但如果我的朋友點擊他頻道中的按鈕,訊息將在兩個頻道中發送。
import random
import string
import discord
from discord_components import DiscordComponents, Button, ButtonStyle
@bot.command()
async def random_screenshot(ctx):
while True:
letters = string.ascii_lowercase string.digits
rand_string = ''.join(random.choice(letters) for i in range(6))
link = "https://prnt.sc/" str(rand_string)
await ctx.send(link,
components=[
Button(style=ButtonStyle.blue, label="Next", emoji="?")])
await bot.wait_for('button_click')
當我使用 while 回圈時,這通常發生在所有命令中
uj5u.com熱心網友回復:
while 回圈不是這里的問題(盡管它是一個單獨的問題)。
發生的事情是await bot.wait_for("button_click")不關心按下了什么按鈕。這意味著當命令運行兩次,然后單擊一個按鈕時,兩個訊息都會回應。
wait_for如果按鈕是我們訊息的按鈕(而不是另一個訊息的按鈕),您需要確保只有繼續。為此,您需要做兩件事。
首先,我們需要生成一個隨機字串并將按鈕的自定義 id 設定為它。這樣我們就可以根據自定義 id 知道按下了哪個按鈕。但是等等,當我們創建Button物件時,discord_components 庫已經為我們生成了一個 ID ,所以我們可以像這樣記住它的 ID:
button = Button(style=ButtonStyle.blue, label="Next", emoji="?")
button_id = button.custom_id
await ctx.send(link, components=[button])
其次,我們需要傳遞一個函式wait_for作為 check 關鍵字引數,如果單擊的按鈕是我們的按鈕,則該函式僅回傳 True。像這樣:
def check_interaction(interaction):
return interaction.custom_id == button_id
await bot.wait_for("button_click", check=check_interaction)
現在你的命令應該只回應它自己的按鈕按下:D
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/317975.html
上一篇:如何在不寫入磁盤的情況下解壓縮?
下一篇:Python代碼說明——整數拆分
