如何在不同功能之间共享对象

时间:2017-06-05 00:08:28

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

我正在尝试这样做,以便如果用户激活test,它将在聊天室中显示测试菜单,如果同一用户在任何消息上发布反应,它将删除该测试菜单:

import discord, asyncio

client = discord.Client()

@client.event
async def on_message(message):
    if message.content.lower().startswith('test'):
        menu = await client.send_message(message.channel, "test menu")

@client.event
async def on_reaction_add(reaction, user):
    if user == message.author:
        await client.delete_message(menu)

client.run('ClientToken')

但是,代码不会从其他函数中读取message.authormenu等对象。

1 个答案:

答案 0 :(得分:1)

您可以创建一个字典来保存邮件和作者值。

test = {'message': None, 'author': None}

@client.event
async def on_message(message):
    if message.content.lower().startswith('test'):
        menu = await client.send_message(message.channel, "test menu")
        test['message'] = menu
        test['author'] = message.author

@client.event
async def on_reaction_add(reaction, user):
    if user == test['author']:
        await client.delete_message(test['message'])