如何在discord.py自动补全中使用外部文件替代内置大列表?
Discord.py自动补全:导入外部文件条目实现方案
完全可以将内置的饮料列表替换为存储大量条目的外部文件,以下是两种常用的实现方式:
方式一:使用纯文本文件(每行一个条目)
1. 准备外部文件
创建drinks.txt文件,每行写入一个饮料名称:
beer milk tea coffee juice cola sparkling water lemonade
2. 修改自动补全函数
async def drink_autocompletion( interaction: discord.Interaction, current: str ) -> typing.List[app_commands.Choice[str]]: # 读取外部文本文件,过滤空行 try: with open('drinks.txt', 'r', encoding='utf-8') as f: drink_choices = [line.strip() for line in f if line.strip()] except FileNotFoundError: # 文件不存在时返回默认列表作为 fallback drink_choices = ['beer', 'milk', 'tea', 'coffee', 'juice'] # 生成匹配的补全选项 return [ app_commands.Choice(name=choice, value=choice) for choice in drink_choices if current.lower() in choice.lower() ]
方式二:使用JSON文件(支持结构化数据)
如果需要区分显示名称(name)和实际值(value),或者存储更复杂的结构,推荐用JSON文件。
1. 准备外部文件
创建drinks.json文件:
[ {"name": "啤酒", "value": "beer"}, {"name": "牛奶", "value": "milk"}, {"name": "红茶", "value": "tea"}, {"name": "美式咖啡", "value": "coffee"}, {"name": "鲜榨橙汁", "value": "juice"} ]
2. 修改自动补全函数
import json async def drink_autocompletion( interaction: discord.Interaction, current: str ) -> typing.List[app_commands.Choice[str]]: try: with open('drinks.json', 'r', encoding='utf-8') as f: drink_items = json.load(f) except (FileNotFoundError, json.JSONDecodeError): # 异常时返回默认选项 drink_items = [{"name": c, "value": c} for c in ['beer', 'milk', 'tea', 'coffee', 'juice']] # 生成匹配的补全选项 return [ app_commands.Choice(name=item['name'], value=item['value']) for item in drink_items if current.lower() in item['name'].lower() ]
注意事项
- 确保外部文件与Bot脚本在同一目录,或使用绝对路径指定文件位置
- 若条目数量极大,建议在Bot启动时一次性读取文件内容并缓存(比如存入全局变量),避免每次补全请求都重复读取文件
- 务必处理文件读取相关的异常(如文件不存在、编码错误、JSON格式错误),避免Bot崩溃
内容的提问来源于stack exchange,提问作者James_Hawkes
相关产品推荐
相关产品推荐

