音乐机器人 - 添加命令以从PC发布图片



我对自己的编程能力没有信心,一直在上下寻找答案。我已经检查了不和谐的 api 服务器,并且还花了 2 天的 Google 搜索,然后在这里创建帐户以寻求帮助。

我正在使用MusicBot作为我的个人机器人的基础。

我想添加一个命令,让我从计算机上的指定文件夹中发布随机图片。目前,我有以下代码:

def cmd_lood (self, channel):
        my_path = r"C:My PicturesSaved PicturesPixiv Dump" 
        choice = os.path.join(my_path, random.choice(os.listdir(my_path))) 
        return self.send_file('choice','Channel')

在 Discord 中启动命令时,我在 CMD 中收到一个错误,指出:无效参数:目标必须是通道、专用通道、用户或对象。收到 str

我可以寻求一些帮助来让这个机器人成功地从我的 PC 发布图片吗?非常感谢您的任何回复。

send_file(destination, fp, *, filename=None, content=None, tts=False)

因此,通道必须是第一个参数,并且必须是discord.Channel对象或discord.PrivateChannel对象。文件路径或类似文件的对象必须是第二个参数。您可以使用discord.utils.get按频道名称获取频道。

你使用了字符串"选择",而不是变量

因此,正确的代码必须如下所示:

    def cmd_lood (self, channel):
        my_path = r"C:My PicturesSaved PicturesPixiv Dump" 
        channel = discord.utils.get(self.get_all_channels(), name=channel)
        choice = os.path.join(my_path, random.choice(os.listdir(my_path))) 
        return self.send_file(channel, choice)

我还建议使用命令扩展来为命令提供上下文,因为如果机器人可以访问具有此名称的多个通道,则使用 self.get_all_channels() 获取通道的方法可能会返回错误的通道。

使用命令扩展,此代码将如下所示:

import discord
from discord.ext import commands
...
bot = commands.Bot()
...
@bot.command(pass_context=True)
async def cmd_lood (ctx, channel):
     my_path = r"C:My PicturesSaved PicturesPixiv Dump" 
     channel = discord.utils.get(ctx.server.channels, name=channel)
     choice = os.path.join(my_path, random.choice(os.listdir(my_path))) 
     await bot.send_file(channel, choice)

最新更新