I’m developing a discord bot using discord.py. In this block of code, I’m trying to open a select menu after pressing a button. It should go though all available items in csv file (item is available if row[1] == ”) and return them, than put all available items in selectmenu and let user select them. I’ve tried many ways, but don’t get how do i do this.
Also, after selecting an item, it should write user’s discord name to csv file. Would appreciate help.
import discord
from discord import ui
from discord.ext import commands
import os
import csv
from dotenv import load_dotenv
load_dotenv('config.env')
client = commands.Bot(command_prefix='!', intents=discord.Intents.all())
@client.command()
async def item(ctx):
view = ItemButtonMenu()
await ctx.send("Choose an item:", view=view)
class ItemButtonMenu(ui.View):
available_items = []
def __init__ (self, *, timeout=None):
self.available_items = []
super().__init__(timeout=timeout)
@ui.button(label = 'Take item', custom_id = 'take_item', style = discord.ButtonStyle.green)
async def take_item(self, interaction: discord.Interaction, button: ui.Button):
with open('items.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile)
next(csvreader)
self.available_items = [row[0] for row in csvreader if row[1] == '']
guild_id = int(os.getenv('GUILD_ID'))
channel = client.get_channel(ID_OF_CHANNEL) #deleted id of there, but in my code it's alright
view = ItemSelectMenu()
await channel.send(view=view, ephemeral=True)
class ItemSelectMenu(ui.View):
options = [discord.SelectOption(label=item) for item in ItemButtonMenu.available_items]
@ui.select(placeholder='Choose an item', options=options)
async def item_select(self, select: ui.Select, interaction: discord.Interaction):
pass
token: str = os.getenv('TOKEN')
client.run(token)