【问题标题】:Discord.py Getting channel name and server name returns an error messageDiscord.py 获取频道名和服务器名返回错误信息
【发布时间】:2020-06-20 23:55:01
【问题描述】:

我目前正在尝试创建一个不和谐机器人,当有人说出命令时,它会说明他们所在的服务器和频道。我过去能够做到这一点,但过去我使用的是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)

而且我知道它可能会向此人发送消息,但是我目前正在开发我的测试机器人,然后将命令交给我的主要机器人。如果您有更好的想法,请告诉我。我之所以有这个变量,是因为我计划在最终产品中包含这些变量。

如果有任何不妥之处,请告诉我,我会对其进行编辑,以期使其更清晰,并在需要时提供更多上下文。

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 使用我当前拥有的当前async def whereAmI(ctx, *, messageContents): 命令,我将如何告诉它使用传入的上下文?我会用@bot.command(pass_context=True) 替换@bot.command 吗?
    • 您已经在上下文中传递。这是 ctx 参数。上下文自动随命令一起提供。所以不需要pass_context 位:) Docs on Commands
    【解决方案2】:

    这是一个应该如何做的例子。

    @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)
    

    祝你有美好的一天!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-25
      • 2023-04-03
      • 1970-01-01
      • 2021-07-05
      • 2021-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多