Discord Bot ping命令embed嵌入功能实现问题及修复方案
Discord Bot ping命令Embed嵌入功能实现
初始未实现Embed功能的代码(仅发送普通文本消息)
import os @bot.command() async def ping(ctx, *, ipaddr: str = '1.3.3.7'): ip_list = [ipaddr] for ip in ip_list: response = os.popen(f"ping {ip}").read() if "Received = 4" in response: await ctx.send(f"UP {ip} / Ping Successful") else: await ctx.send(f"DOWN {ip} / Ping Unsuccessful")
修复后可正常输出Embed嵌入消息的代码
@bot.command() async def ping(ctx, *, ipaddr: str = '1.3.3.7'): ip_list = [ipaddr] embed = discord.Embed(title='Ping Info:', color=0xFF0000) embed.set_footer(text=f"Requested by {ctx.author}") for ip in ip_list: response = os.popen(f"ping {ip}").read() if "Received = 4" in response: embed.add_field(name=f"{ip} is UP", value="Ping Successful", inline=False) else: embed.add_field(name=f"{ip} is DOWN", value="Ping Unsuccessful", inline=False) await ctx.send(embed=embed)
额外注意事项
- 运行上述代码前需确保已导入discord库,若提示
discord未定义,补充import discord语句即可 - 当前ping结果判断逻辑仅适配Windows系统,Linux/macOS系统默认ping返回格式不同,需调整判断条件为对应系统的返回值特征
os.popen为阻塞调用,若ping目标响应慢会阻塞Bot其他指令的响应,性能优化可改用aioping等异步ping库
内容的提问来源于stack exchange,提问作者Randomz
相关产品推荐
相关产品推荐

