You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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 a discord.Embed object and assigning it to the embed variable. Python has no idea what embed is at that point!
  • When you did create the discord.Embed instance, you didn't assign it to the embed variable — so that object was just created and immediately discarded, leaving embed still 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 embed variable with a discord.Embed instance, setting the title correctly.
  • The set_image() method requires a url keyword 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 hugs list (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:10:04