Discordpy: Efficient Invitation Checking
I'm attempting to write a function using the discord.py library. The function is intended to reward a specific user for inviting another user.
The current code I have does indeed work, but I'm worried about the efficiency of the code. Particularly in these two situations:
- If many users join in quick succession
- If there are many users in the server (100k+)
My Code:
@client.event
async def on_ready():
global members_joined
MAIN_GUILD = client.get_guild() # ID Redacted
# Get a list of users in the server. This is to prevent additional rewards on leave+rejoin
invites_before_join = await MAIN_GUILD.invites()
members_joined = await MAIN_GUILD.fetch_members(limit=None).flatten()
@client.event
async def on_member_join(member):
global invites_before_join
invites_after_join = await member.guild.invites()
for before_invite in invites_before_join:
for after_invite in invites_after_join:
if(before_invite.code == after_invite.code and before_invite.uses < after_invite.uses):
if(member not in members_joined):
# code here (redacted)
members_joined.append(member) # Add them to the list, so they cannot leave+rejoin to reactivate
invites_before_join = invites_after_join
return
As you can see, in my solution I use a nested for loop. I'm wondering if this is something I should be concerned about in terms of efficiency (particularly for the two reasons stated above). The reason I had to do it this way was because I needed the name and ID of the inviter, so I can reward them.
Solution 1:
After being suggested https://github.com/cyrus01337/invites, I took a look and found a more elegant solution using async def on_invite_update(member, invite):
Thank you Lukasz in the comments for the suggestion.