discord.py执行meme命令报get未定义NameError的修复方法
报错根因
你遇到的NameError: name 'get' is not defined是典型的名称未定义错误,触发点在meme指令的HTTP请求逻辑:
- 代码中调用
get()方法请求梗图API,但你既没有安装对应的HTTP请求库,也没有在代码顶部导入该方法,Python运行到这行时找不到名为get的可调用对象,直接抛出异常。 - 修复这个问题后你还会遇到第二个同类错误:meme指令里写的
color = colors.purple同样没有定义colors对象,会继续报NameError。 - 额外提醒:你代码中的等级系统模块存在严重缩进错误,所有等级相关的监听器、指令全部被嵌套在了
say指令函数内部,永远不会被加载运行,且代码中未定义levels类,对应的setup函数也会报错,这部分属于其他功能的问题,不影响meme指令运行。
修复方案
步骤1:安装依赖、补全导入
- 打开终端运行以下命令安装HTTP请求库:
pip install requests - 在代码顶部的导入区域补充两行导入,解决名称找不到的基础问题:
(补充import discord import requestsimport discord是为了避免你调用discord.Embed、discord.Game等对象时出现潜在导入错误)
步骤2:修正meme指令代码
把原有meme指令替换为以下可运行版本,同时解决get未定义、colors.purple未定义两个问题,还加了基础的请求异常判断,避免API挂掉的时候机器人直接崩溃:
@bot.command(pass_context=True, description='some fresh memes for you!') async def meme(ctx): # 调用requests库的get方法请求API resp = requests.get("https://meme-api.herokuapp.com/gimme/dankmemes") # 接口请求失败时直接抛出错误终止流程 resp.raise_for_status() # 直接解析接口返回的JSON数据,不用手动json.loads data = resp.json() # 紫色直接用十六进制色值0x9B59B6,替换不存在的colors.purple meme_embed = discord.Embed( title=data['title'], url=data['postLink'], color=0x9B59B6, timestamp=ctx.message.created_at ) meme_embed.set_image(url=data['url']) meme_embed.set_footer(text=f'Used by {ctx.author.name}', icon_url=ctx.author.avatar_url) await ctx.reply(embed=meme_embed)
可选优化(解决请求阻塞问题)
上面用的requests是同步库,请求API的时候会卡住整个机器人的事件循环,服务器人数多、指令调用频繁的时候会出现机器人无响应的情况,追求稳定可以换成异步HTTP库aiohttp:
- 安装依赖:
pip install aiohttp - 顶部补充导入
import aiohttp,把meme指令替换为异步版本:@bot.command(pass_context=True, description='some fresh memes for you!') async def meme(ctx): async with aiohttp.ClientSession() as session: async with session.get("https://meme-api.herokuapp.com/gimme/dankmemes") as resp: data = await resp.json() meme_embed = discord.Embed( title=data['title'], url=data['postLink'], color=0x9B59B6, timestamp=ctx.message.created_at ) meme_embed.set_image(url=data['url']) meme_embed.set_footer(text=f'Used by {ctx.author.name}', icon_url=ctx.author.avatar_url) await ctx.reply(embed=meme_embed)
验证方式
改完代码后重启机器人,发送f!meme即可正常拉取并推送梗图。
内容的提问来源于stack exchange,提问作者Happy Deer
相关产品推荐
相关产品推荐

