Discord.py 正在获取频道名称和服务器名称 returns 一条错误消息

Discord.py Getting channel name and server name returns an error message

我目前正在尝试创建一个 discord 机器人,当有人说出命令时,它会说明他们所在的服务器和频道。我过去能够做到这一点,但过去我使用的是 on_message(message)if message.content.startswith('$hello')。我最近开始使用 @bot.command,但我仍在努力适应它。我尝试使用 message.guild.namemessage.channel.mention 但我收到一条错误消息。 Undefined variable 'message' 我认为这是因为在我的旧设置中,我在 on_message(message) 中定义了消息,但是在我当前的代码中它似乎不起作用。

import discord
import asyncio
from discord.ext import commands
botToken = token
bot = commands.Bot(command_prefix = '#')
client = discord.Client()
@bot.event
async def on_ready():
    print('Bot is online and ready.')
@bot.command()
async def whereAmI(ctx, *, messageContents):
    link = await ctx.channel.create_invite(max_age = 300)
    message = 'You are in {message.guild.name} in the {message.channel.mention} channel with an invite link of ' + link
    await ctx.message.author.send(message)
bot.run(botToken)

而且我知道它可能会私信这个人,但是在我将命令移交给我的主要机器人之前,我目前只在测试我的机器人。如果您有任何更好的想法,请告诉我。我有变量的原因是因为我计划在最终产品中包含变量。

如果有任何不明白的地方,请告诉我,我会对其进行编辑,希望能使其更加清晰,并在需要时提供更多上下文。

要获取消息对象,您需要使用传入的“上下文”(ctx)。所以它将是 ctx.message.guild.namectx.message.channel.mentionDocs on Context

另一方面,Bot 是 Client 的子类。因此,无论 Client 能做什么,Bot 也能做什么。您不需要客户端和机器人,只需要机器人。 Docs on Bot subclass

这是一个示例。

@bot.command()
async def whereAmI(ctx, *, messageContents):
    link = await ctx.channel.create_invite(max_age = 300)
    message = f'You are in {ctx.message.guild.name} in the {ctx.message.channel.mention} channel with an invite link of ' + link
    await ctx.message.author.send(message)

祝你有个愉快的一天!