【问题标题】:Discord bot in pythonpython中的不和谐机器人
【发布时间】:2021-02-28 03:43:53
【问题描述】:

我正在尝试制作一个不和谐的机器人,当用户键入!goat 时,它会发送山羊的随机图像(位于文件夹中)。但我无法到达那里,也找不到像我这样的案例。

这是我的代码:

import discord
import random
import os

class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged in as')
        print(self.user.name)
        print(self.user.id)
        print('------')

    async def on_message(self, message):
        # we do not want the bot to reply to itself
        if message.author.id == self.user.id:
            return

        if message.content.startswith('!goat'):

            with open(random.choice(os.listdir("/home/leo/Bureau/bot-discord/image")), 'rb') as f:
                picture = discord.File(f)
                await channel.send(channel, picture)

感谢您的回答。

【问题讨论】:

  • listdir 返回文件名,而不是完整路径。
  • 哦,好吧,这是个问题,哈哈。你有什么我可以使用的方法吗?
  • @LéoCarrez 为什么不将路径存储在变量中,然后将路径和文件名连接起来?
  • 看看glob.glob。我认为这正是您正在寻找的。​​span>
  • 因为我的代码有效,他在我的文件夹中随机拍摄了一张图片,但他没有发送不和谐的图片,他返回如下错误:FileNotFoundError: [Errno 2] No such file or directory: '图片的名称。

标签: python python-3.x discord bots discord.py


【解决方案1】:

我认为您可以使用glob.glob 解决您的问题:

import glob
from pprint import pprint
from random import choice

goats = glob.glob("P:/Goats/*.png")
pprint(goats)
print(choice(goats), "is the chosen one!")

输出:

['P:/Goats\\Goat0.png',
 'P:/Goats\\Goat1.png',
 'P:/Goats\\Goat2.png',
 'P:/Goats\\Goat3.png',
 'P:/Goats\\Goat4.png',
 'P:/Goats\\Goat5.png',
 'P:/Goats\\Goat6.png',
 'P:/Goats\\Goat7.png',
 'P:/Goats\\Goat8.png',
 'P:/Goats\\Goat9.png']
P:/Goats\Goat2.png is the chosen one!

【讨论】:

  • 感谢您的代码有效,但我不知道如何在频道 discord 上发送图片
  • 使用discord.File:channel.send(file=discord.File(fp="path/to/file.png", filename="image.png"))
  • @LéoCarrez 您必须定位发送消息的渠道。我不是 100%,但您应该能够在原始代码中通过 message.channel 访问通道对象。
  • 你知道我该怎么做吗,因为我试图在 discord.py 文档上找到它,但我不明白它是如何工作的。
【解决方案2】:

我终于在几个论坛和文档上找到了答案。所以我的代码是:

import discord
import glob
from pprint import pprint
from random import choice

class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged in as')
        print(self.user.name)
        print(self.user.id)
        print('------')

    async def on_message(self, message):
        # we do not want the bot to reply to itself
        if message.author.id == self.user.id:
            return

        if message.content.startswith('!goat'):

            goat = glob.glob("/home/leo/Bureau/bot-discord/image/*.jpeg")
            pprint(goat)
            image = choice(goat)

            await message.channel.send(file=discord.File(image))

感谢大家的回答。祝你有美好的一天。

【讨论】:

    猜你喜欢
    • 2021-10-30
    • 2021-05-27
    • 2021-07-15
    • 2021-08-18
    • 2021-03-29
    • 2021-07-11
    • 2021-03-25
    • 2018-08-13
    • 1970-01-01
    相关资源
    最近更新 更多