Repository: Pycord-Development/pycord

Issue:
autocomplete issues.
### Summary

autocomplete double pings when option is first loaded and if you switch to a different autocomplete option before the first sends to discord it will give you the result of the first autocomplete instead of the second.

### Reproduction Steps

Double ping bug:
The autocomplete function always gets called twice even if there is no delay.
This also happens when you return to the option even if there is already text in it.

Wrong autocomplete function:
The first autocomplete has to take a bit to get results or take a while to ping the server. In the example I used a wait of 1 second but this bug can occur even if the wait is as low as 0.1 sec.
It is hard to get the timing right on computer but on mobile it pings with the autocomplete function after the user clicks an autocomplete result making this bug super common.

https://user-images.githubusercontent.com/70595776/159508099-3aa4989d-5cbe-4e14-90a8-6f325b098af6.mp4

### Minimal Reproducible Code

```python
bot = commands.Bot()
gid = [gidid]

async def test_autocomplete(ctx: discord.AutocompleteContext):
  print(f"test 1, value = {ctx.value}")
  await asyncio.sleep(1)
  return ["test 1 autocomplete", "output"]
async def test_two_autocomplete(ctx: discord.AutocompleteContext):
  print(f"test 2, value = {ctx.value}")
  return ["test 2 autocomplete", "output"]
  
@bot.slash_command(name = "test", description = "test." , guild_ids = gid)
async def test(ctx, test: Option(str, "test", autocomplete=test_autocomplete), test_two: Option(str, "test", autocomplete=test_two_autocomplete)):
  await ctx.respond(f"test {test}, test 2 {test_two}")

bot.run(token)
```


### Expected Results

The autocomplete function gets called once initially and when you switch the the second option it should use the second autocomplete function.

### Actual Results

The first autocomplete function gets called twice initially and when the user switches to the second option it shows the autocomplete result from the first option.

### Intents

all

### System Information

- Python v3.10.3-final
- py-cord v2.0.0-beta
    - py-cord pkg_resources: v2.0.0b5
- aiohttp v3.8.1
- system info: Windows 10 10.0.19042

### Checklist

- [X] I have searched the open issues for duplicates.
- [X] I have shown the entire traceback, if possible.
- [X] I have removed my token from display, if visible.

### Additional Context

_No response_


Discussion:
Can you try reproducing this bug but typing slower? It almost looks like you typed so fast that your client didn't send any requests, this might be a discord-side issue.
> Can you try reproducing this bug but typing slower? It almost looks like you typed so fast that your client didn't send any requests, this might be a discord-side issue.

For PC you need to type fast for the first autocomplete to still be processing during the time you switch to the next autocomplete, this bug can also happen where it shows the second autocomplete for a second than switches to the first. I think in the video I attached the second autocomplete got the list from the first before it could even ask the bot for it's own. On mobile this bug happens a lot when switching from one autocomplete to another because it pings discord for the autocomplete then immediately goes to the next.
The double in the beginning happens no matter what though.
> For PC you need to type fast for the first autocomplete to still be processing during the time you switch to the next autocomplete, this bug can also happen where it shows the second autocomplete for a second than switches to the first. I think in the video I attached the second autocomplete got the list from the first before it could even ask the bot for it's own. On mobile this bug happens a lot when switching from one autocomplete to another because it pings discord for the autocomplete then immediately goes to the next. The double in the beginning happens no matter what though.

This honestly sounds more like a discord issue than anything. There's not really anything we can do in cases like this.
After looking further at this, while it's somewhat still an issue with the API, it's causing a preventable race condition in the library. I've implemented a fix and will open a PR for it.

Resolving patch:
diff --git a/discord/bot.py b/discord/bot.py
--- a/discord/bot.py
+++ b/discord/bot.py
@@ -743,14 +743,28 @@ async def process_application_commands(self, interaction: Interaction, auto_sync
                 return self.dispatch("unknown_application_command", interaction)
 
         if interaction.type is InteractionType.auto_complete:
-            ctx = await self.get_autocomplete_context(interaction)
-            ctx.command = command
-            return await command.invoke_autocomplete_callback(ctx)
+            return self.dispatch("application_command_auto_complete", interaction, command)
 
         ctx = await self.get_application_context(interaction)
         ctx.command = command
         await self.invoke_application_command(ctx)
 
+    async def on_application_command_auto_complete(self, interaction: Interaction,
+                                                   command: ApplicationCommand) -> None:
+        async def callback() -> None:
+            ctx = await self.get_autocomplete_context(interaction)
+            ctx.command = command
+            return await command.invoke_autocomplete_callback(ctx)
+
+        autocomplete_task = self.loop.create_task(callback())
+        try:
+            await self.wait_for("application_command_auto_complete", check=lambda i, c: c == command, timeout=3)
+        except asyncio.TimeoutError:
+            return
+        else:
+            if not autocomplete_task.done():
+                autocomplete_task.cancel()
+
     def slash_command(self, **kwargs):
         """A shortcut decorator that invokes :func:`command` and adds it to
         the internal command list via :meth:`add_application_command`.


Test patch: