简体   繁体   中英

How to solve telethon UnboundLocalError

I get this error on the last line of my code. If anyone has encountered with the same problem, I'll be glad to share with me on how to solve it. The source code is telethon based and is full. The execution is also successful but when wanna give response to userid it gives the UnboundLocalError.

The codes:

@client.on(events.NewMessage(incoming=True, from_users=(723428565, 677543378)))
async def _(event):
    if event.fwd_from:
        return
    url = "http://www.google.com" 
    if event.reply_to_msg_id and "allow" in event.raw_text:
        previous_message = await event.get_reply_message()
        previous_message_text = previous_message.message
        if previous_message.media:
            downloaded_file_name = await client.download_media(
                previous_message,
                path, 
            )
            surl = "{}/searchbyimage/upload".format(url)
            multipart = {
                "encoded_image": (
                    downloaded_file_name,
                    open(downloaded_file_name, "rb"),
                ),
                "image_content": "",
            }
            google_rs_response = requests.post(
                surl, files=multipart, allow_redirects=False
            )
            the_location = google_rs_response.headers.get("Location")
            os.remove(downloaded_file_name)
        else:
            previous_message_text = previous_message.message
            surl = "{}/searchbyimage?image_url={}"
            request_url = surl.format(url, previous_message_text)
            google_rs_response = requests.get(request_url, allow_redirects=False)
            the_location = google_rs_response.headers.get("Location")
        headers = {
            "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0"
        }
        response = requests.get(the_location, headers=headers)
        soup = BeautifulSoup(response.text, "html.parser")
        bro = soup.find_all("div", {"class": "r5a77d"})[0]
        lol = bro.find("a")
        url + lol.get("href")
        final = lol.text
    await event.edit(
        event.chat_id, final.replace("me", "")
    ) 

Error:

Line 42: UnboundLocalError: local variable 'final' referenced before assignment

You are defining the variable text = lol.text inside the if block if "allow" in event.raw_text:

So it looks like your condition wasn't met, and the variable text was never defined. So when you tried to access it await event.edit(event.chat_id, text.replace("me", "")) you got an error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM