hey im making a giveaway command but it throws a error "'async_generator' object has no attribute 'flatten'"

Question:

so im making a giveaway command for my bot
in discord.py v2 but it throws this error: ‘async_generator’ object has no attribute ‘flatten’

here is an image:
getting the error

my code –

@client.command(description="Starts a giveaway.")
@has_permissions(manage_messages=True)
async def gcreate(ctx, mins: int, *, prize: str):
    global users, new_msg
    try:
        em = discord.Embed(
            title=f"<a:fun:1052215771738165269> {prize} <a:fun:1052215771738165269>",
            color=discord.Colour.random()
        )
        # end = datetime.datetime.utcnow() + datetime.timedelta(seconds=mins *60)
        timestamp = time.time() + mins
        em.set_footer(text=f"Started by {ctx.author}")
        em.add_field(name=f"** **", value=f"**Ends at**: <t:{int(timestamp)}:f> or <t:{int(timestamp)}:R> n **Prize**: {prize} n **Hosted by**: {ctx.author.mention}", inline=False)
        my_msg = await ctx.send(embed=em)
        await my_msg.add_reaction(" ")
        await asyncio.sleep(mins)
        new_msg = await ctx.channel.fetch_message(my_msg.id)
        users = await new_msg.reactions[0].users().flatten()
        users.pop(users.index(client.user))
        winner = random.choice(users)
        await ctx.send(f'Congratulations {winner.mention} won **{prize}**! Hosted by {ctx.author.mention}')
        em = discord.Embed(
            title=f"Hey! you won **{prize} GG**!",
            description="Join the dev's server https://discord.gg/notsetyet <:",
            color=0xff2424
        )
        em.set_author(name=winner.name, icon_url=winner.avatar_url)
        await winner.send(embed=em)
    except Exception as er:
        await ctx.send(er)

@client.command(description="Rerolls the recent giveaway.")
@has_permissions(manage_messages=True)
async def reroll(ctx, channel: discord.TextChannel, id):
    try:
        new_message = await channel.fetch_message(id)
    except:
        await ctx.send("Incorrect id.")
        return

    users = await new_message.reactions[0].users().flatten()
    users.pop(users.index(client.user))
    winner = random.choice(users)

    reroll_announcement = discord.Embed(color = 0xff2424)
    reroll_announcement.set_author(name = f'The giveaway was re-rolled by the host!', icon_url = 'https://i.imgur.com/DDric14.png')
    reroll_announcement.add_field(name = f'  New Winner:', value = f'{winner.mention}', inline = False)
    await channel.send(embed = reroll_announcement)

i know that flatten has been removed in discord.py v2 but i dont know how to implement the new one
im confused any type of help will be appreciated!

Asked By: I am goku

||

Answers:

The discord.Reaction.users were changed to return an async generator (PEP 525) and have to be turned into a list in your use case. You can easily do it using list comprehension like:

users = [user async for user in reaction.users()]

Instead of:

users = await new_msg.reactions[0].users().flatten()

The example of this can be found in discord.py discord.Reaction.users document.

Answered By: Catgal

i had the same issue, but i fixed that! Code |
V

import discord
from discord.ext import commands
from discord.ui import Button, View
import random
from random import *
import random as random

@bot.command
async def gw(ctx, channel: discord.TextChannel, name, description, time: int, requirement: discord.Role = None, color: discord.Color = None):
    if color == None: #if no color is entered:
        color = discord.Color.blue() #sets the embed color to blue
    
    enters = [] #enters list (when someone presses the enter button)
    running = True # is the gw running variable
    creator = ctx.message.author.name #gw creator's name
    gwaem=discord.Embed(title= "Giveaway! - " + fr"{name}", url="", description=fr"{description}", color=color) #root gw embed
    gwaem.set_footer(text="Hosted By: " + fr"{creator}" + " | " + " Ends From Now in: " + fr"{time}" + " minutes")
    button = Button(label="Enter", style=discord.ButtonStyle.green) #enter button
    
    async def button_callback(interaction): #when someone pressed the enter button
        author = interaction.user #who triggerd the button
        if requirement == None: #if no require rank granted:
            if author in enters:
                if running != True:
                    await interaction.response.send_message("This Giveaway Has Ended!", ephemeral = True)
                else:
                    await interaction.response.send_message("You Have Alredy Entered This Giveaway!", ephemeral = True)
            else:
                enters.append(author)
                await interaction.response.send_message("Now You Entered The Giveaway!", ephemeral = True)
        else: #else if requirement variable isn't empty
            if author in enters:
                if running != True:
                    await interaction.response.send_message("This Giveaway Has Ended!", ephemeral = True)
                else:
                    await interaction.response.send_message("You Have Alredy Entered This Giveaway!", ephemeral = True)
            else:
                if requirement in author.roles:
                    enters.append(author)
                    await interaction.response.send_message("Now You Entered The Giveaway!", ephemeral = True)
                elif requirement not in author.roles:
                    await interaction.response.send_message("You Have Missing " + fr"{requirement.mention}" + " Role To Enter This Giveaway!", ephemeral = True)
            
    button.callback = button_callback
            
    view = View()
    view.add_item(button)
    await channel.send(embed=gwaem, view=view)


    await asyncio.sleep(time*60) # starts the gw countdown
    
    
    if not enters: #if no one has entered the gw
        running = False
        await channel.send("It's Looks Like no one has entered the giveaway!")
    else:
        running = False
        winner = random.choice(enters)
        await channel.send(winner.mention + " Has Won The Giveaway")
Answered By: Balázs Kókai
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.