首页 > 解决方案 > 在异步函数中使用全局变量不起作用

问题描述

我的程序应该做的是在用户键入 ~modmail 的不和谐服务器中。然后此消息到达他们的 dm:

在此处输入图像描述

然后,用户应在 dm 中回复指定的问题。然后将所有这些信息发送到原始服务器中的特定名称通道。

现在问题来了:全局变量不能在新的 on_message 函数中使用:

    name = "reports-log"
    channel = get(message.server.channels, name=name, type=discord.ChannelType.text)
    original = message.author

    dm_embed=discord.Embed(title="Modmail/Support:", color=discord.Color.green(), description=" ")
    dm_embed.add_field(name="Please declare your problem/question and send it in this channel!", value="**Question must be on one message**\n*You can make a new line if you press Shift + Enter*")
    dm_embed.set_footer(text="Valid for 1 minute")
    await client.send_message(message.author, embed=dm_embed)

    @client.event
    async def on_message(message):
        if message.server is None and message.author != client.user:
            global channel
            global original

            question = message.content

            report_embed = discord.Embed(title="New Modmail:" , color=discord.Color.green())
            report_embed.add_field(name="User: ", value=message.author.mention)
            report_embed.add_field(name="Question: ", value=question)

            await client.send_message(channel, embed=report_embed)

            await client.send_message(original, embed=discord.Embed(color=discord.Color.green(), description="Your support request has been recieved, you will recieve help shortly."))

不知道为什么这些变量不能在我的函数中使用。希望有人为我提供解决方案。谢谢。

标签: python-3.xdiscord.py

解决方案


与其尝试将全局变量用于需要上下文隔离的函数,不如尝试将事物保持在同一次运行中。
如果第二个用户尝试在第一个用户发送 modmail 的过程中,您将最终original用第二个用户覆盖您的全局。

正如对您问题的评论中提到的,您的问题可以通过使用client.wait_for_message而不是全局变量来解决。

第二个问题是您试图通过搜索客户端的缓存在全局范围内定义不和谐变量,直到您调用client.run()或您首选的启动机制之后才会填充这些变量。

# You can still store a global channel, but must find it after you start
@client.event
async def on_ready():
    # This is only called once the client has downloaded all its data.
    global channel
    channel = get(...)

def message_mods(message):
    request = await client.send_message(message.author, ....)

    response = await client.wait_for_message(60,
        author = message.author,
        channel = request.channel
    )

    # Generate report embed using the `response` object
    e = discord.Embed(title="New modmail.", colour=discord.Colour.green(),
                      description=response.content)
    e.set_author(name=response.author.name, icon_url=response.author.avatar_url)

    # Use the channel found in on_message, no need for global
    # because we didn't redefine channel at all.
    client.send_message(channel, embed=e)

    # Reply to the user
    client.send_message(response.channel, ...)

推荐阅读