微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

尝试从本地字典中查找要发布的图片时出现 Discord.py bot 错误

如何解决尝试从本地字典中查找要发布的图片时出现 Discord.py bot 错误

我一直试图让我的 discord.py 机器人在使用命令 !meme 调用时从本地字典中发布 random_image。但是过程中出了点问题,并向我返回了错误消息:

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\viodo\PycharmProjects\pythonProject\venv\lib\site-packages\discord\client.py",line 343,in _run_event
    await coro(*args,**kwargs)
  File "C:\Users\viodo\PycharmProjects\pythonProject\bot.py",line 43,in on_message
    await message.channel.send(file=discord.File(random_image))
  File "C:\Users\viodo\PycharmProjects\pythonProject\venv\lib\site-packages\discord\file.py",line 73,in __init__
    self.fp = open(fp,'rb')
FileNotFoundError: [Errno 2] No such file or directory: '3b202f6.jpg'

有问题的代码

import discord
from discord.ext import commands
import random
import os
client = commands.Bot(command_prefix = ".")

@client.event
async def on_ready():
    print("Bot is in the HOUSE!")

@client.event
async def on_message(message):
    if message.author == client.user:
        return

#__________________________________________________________________________
    random_quotes = [
        ("I'm a bot,bing bong"),('Hej'),("Hello"),("Yes yes yes yes yes"),]

    if message.content == '!bot':
        response = random.choice(random_quotes)
        await message.channel.send(response)
#_________________________________________________________________________
    specified_meme = [r"C:\Users\viodo\memes\Scotland icetruck salter GPS.png"]

    if message.content == '!meme2':
        random_meme = random.choice(specified_meme)
        await message.channel.send(file=discord.File(random_meme))
#__________________________________________________________________________

    meme = []
    for root,dirs,files in os.walk(r'C:\Users\viodo\memes'):
        for file in files:
            if file.endswith('.jpg'):
                meme.append(file)
    random_image = random.choice(meme)

    if message.content == "!meme":
        await message.channel.send(file=discord.File(random_image))

client.run("xxxx")

问题是,从我所见,它确实找到了一个文件,因为它在错误消息中显示文件 3b202f6.jpg,该文件是来自指定目录的图片。怎么可能...我尝试隔离图像拾取代码,它运行顺利,在终端中输出随机图像,让我更加困惑。更糟糕的是,昨天大约半小时,一切都很顺利,然后无缘无故地出现了错误

为了确保字典不是问题或找到它,我编写了另一行代码,当调用 !meme2 时,它从 sat 字典中选择了一个指定的图像 Scotland icetruck salter GPS.png 并且它起作用了就像它应该做的那样。

解决方法

您无法从计算机上传图片。您必须使用链接。不要使用网站来执行此操作,只需将您想要的图像粘贴到不和谐中即可。然后右键单击它并按“复制链接”。然后将此链接用作消息中的图像。 我还建议使用 @client.command(),因为它更容易、更快、更干净。

import discord
from discord.ext import commands

token = ""

client = commands.Bot(command_prefix = "Whatever you want")

@client.event
async def on_ready():
    print("Bot is online")

@client.command()
async def image(ctx):
    await ctx.send("image link")

client.run(token)

来自 discord 的链接将如下所示: https://media.discordapp.net/attachments/xxxxxxxxx/xxxxxxxxx/unknown.png(文件扩展名可能不同)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。