使用Discord.py开发机器人遇UnboundLocalError报错求助
Fixing UnboundLocalError in Discord.py .hug Command
Let's break down why you're hitting that UnboundLocalError and fix it step by step:
The Root Cause
Your code has two key issues that lead to the error:
- You tried to call
embed.set_image()before ever creating adiscord.Embedobject and assigning it to theembedvariable. Python has no idea whatembedis at that point! - When you did create the
discord.Embedinstance, you didn't assign it to theembedvariable — so that object was just created and immediately discarded, leavingembedstill undefined.
Corrected Code
Here's the fixed version of your .hug command, with comments explaining the changes:
import random # Make sure this is at the top of your file import discord from discord.ext import commands @commands.command(name="hug") async def hug(self, ctx): hugs = [ 'https://tenor.com/view/anime-neko-k-on-hug-friends-gif-13124779', 'https://tenor.com/view/anime-hug-love-smile-gif-15942846', 'https://tenor.com/view/toilet-bound-hanakokun-anime-anime-hug-gif-16831471', 'https://tenor.com/view/neko-anime-hug-gif-10989534' ] hugsrandom = random.choice(hugs) # 1. First create the Embed object and assign it to 'embed' embed = discord.Embed(title=f"**Вы обняли@{ctx.message.author.id}** ") # 2. Then call set_image() on the existing embed (note the `url=` parameter) embed.set_image(url=hugsrandom) # 3. Send the properly initialized embed await ctx.send(embed=embed)
Key Fixes Explained
- We first initialize the
embedvariable with adiscord.Embedinstance, setting the title correctly. - The
set_image()method requires aurlkeyword argument to specify the image link — your original code was missing this, which would have caused a second error once you fixed the first one. - We removed the unnecessary parentheses around each URL in the
hugslist (they don't break anything, but they're redundant).
Now your .hug command should work as expected, sending a random hug GIF in a nicely formatted embed!
内容的提问来源于stack exchange,提问作者Whitefin
相关产品推荐
相关产品推荐

