Home > Blockchain >  For loop channel history Discord.py
For loop channel history Discord.py

Time:01-08

I am having trouble trying to get a for loop to work here. There error I get when trying to run is users = await reaction.users() TypeError: object async_generator can't be used in 'await' expression. I am pretty beginner at Async/Await. The goal of this code is to iterate through the reactions on messages in the 3 channels in the array. Any direction here would be greatly appreciated.

@client.event
async def on_message(message):

if message.content == "/react":
            channel_ids= [12345, 67891, 12341]
            insert_query = "Insert into lnd_reaction (message_id, emoji, member_name, channel_id, active) values (%s, %s, %s, %s, %s)" 
            total = len(channel_ids)
            
            for i in range(total):
                channel = client.get_channel(channel_ids[i])
                async for msg in channel.history(limit=None):  
                    users = [] 
                    for reaction in msg.reactions:
                        users = await reaction.users()
                        for u in users:
                            if u != client.user.name:
                                print(msg.id, reaction, u, msg.channel, 1)
                                insert_values = (msg.id, str(reaction), str(u), msg.channel.id, 1)                        
                                try:
                                    cursor.execute(insert_query, insert_values)
                                    cnx.commit() 
                                except Exception as e:
                                    print("Error at:")
                                    print(e) 
                                    print("Exiting...")
                                    exit()  

CodePudding user response:

reaction.users() is a generator, not a function. You can't await it, but you have to loop over it.

Just like you're doing above for the history, you can use async for to loop over it.

async for user in reaction.users():
    ...

More info in the Migration Guide: https://discordpy.readthedocs.io/en/stable/migrating.html#moving-away-from-custom-asynciterator

Also instead of manually parsing messages in on_message, consider using commands.

PS instead of for i in range(len(some_list)), just use for item in some_list. It's a lot cleaner.

  • Related