Ubuntu 22.04下Discord.py SSL证书验证失败问题求助
Ubuntu 22.04下Python虚拟环境运行Discord机器人遇SSL证书验证失败的解决办法
问题现象
在Ubuntu 22.04系统中,使用Python虚拟环境运行Discord机器人代码时,抛出以下SSL证书错误:
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)')]
已尝试更新certifi、手动下载证书等操作,均未解决问题,机器人无法正常连接Discord。
机器人代码
import discord from discord.ext import commands,tasks import os from dotenv import load_dotenv load_dotenv() # Get the API token from the .env file. DISCORD_TOKEN = os.getenv("discord_token") intents = discord.Intents().all() client = discord.Client(intents=intents) bot = commands.Bot(command_prefix='.',intents=intents) ffmpeg_options = { 'options': '-vn' } @bot.command(name='join', help='Tells the bot to join the voice channel') async def join(ctx): if not ctx.message.author.voice: await ctx.send("{} is not connected to a voice channel".format(ctx.message.author.name)) return else: channel = ctx.message.author.voice.channel await channel.connect() @bot.command(name='leave', help='To make the bot leave the voice channel') async def leave(ctx): voice_client = ctx.message.guild.voice_client if voice_client.is_connected(): await voice_client.disconnect() else: await ctx.send("The bot is not connected to a voice channel.") @bot.command(name="teiku", help="teikuuuuuuuu") async def teiku(ctx): try : server = ctx.message.guild voice_channel = server.voice_client async with ctx.typing(): voice_channel.play(discord.FFmpegPCMAudio(executable="ffmpeg.exe", source="teiku.com/teiku")) except: await ctx.send("The bot is not connected to a voice channel.") if __name__ == "__main__" : bot.run(DISCORD_TOKEN)
注:代码中teiku.com链接为替代链接,实际为指向.wav文件的短链接,与问题无关。
解决方案
1. 安装系统根证书包
Ubuntu系统默认根证书可能不全,先安装官方根证书套件:
sudo apt update && sudo apt install -y ca-certificates
2. 强制虚拟环境使用系统根证书
Python虚拟环境默认优先使用自身certifi包的证书,可通过环境变量强制让依赖的aiohttp调用系统证书:
- 临时生效:启动机器人前执行
export SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt - 永久生效:在Python代码开头添加
import os os.environ['SSL_CERT_FILE'] = '/etc/ssl/certs/ca-certificates.crt'
3. 更新系统证书存储
安装证书后更新系统证书索引:
sudo update-ca-certificates
4. 替换虚拟环境certifi证书文件
如果虚拟环境仍使用自身证书,直接替换为系统证书:
# 查找虚拟环境中certifi的证书路径 python -c "import certifi; print(certifi.where())" # 替换为系统证书 sudo ln -sf /etc/ssl/certs/ca-certificates.crt $(python -c "import certifi; print(certifi.where())")
额外修正
代码中ffmpeg.exe是Windows平台的可执行文件名,Ubuntu系统需改为ffmpeg,同时确保已安装ffmpeg:
sudo apt install -y ffmpeg
修改代码对应行:
voice_channel.play(discord.FFmpegPCMAudio(executable="ffmpeg", source="你的音频链接"))
内容的提问来源于stack exchange,提问作者Benyamin
相关产品推荐
相关产品推荐

