全局变量不会改变事件内部的值

时间:2018-09-03 02:30:50

标签: python function global-variables discord discord.py

命令!et_as创建一个事件,每当有人发送消息10秒钟,该事件就会使计数器增加1。
在10秒结束时,机器人会说出发送了多少消息,并开始进行3小时的冷却。
唯一的问题是,发出第一个!et_as命令后,指示事件是否发生的变量FeastActive不会改变。

@theclient.event
async def on_message(message):
    global FeastActive
    global Feast
    global FeastCount

    if message.author == theclient.user:
        return

    if FeastActive == True: 
        FeastCount += 1
        await theclient.send_message(message.channel, ' NOM NOM NOM')

    if message.content.startswith('!hello'):
        msg = 'Hello {0.author.mention}'.format(message)
        await theclient.send_message(message.channel, msg)

    if message.content.startswith('!joke'):
        r = requests.get('https://icanhazdadjoke.com', headers={"Accept":"application/json"}).text
        l = json.loads(r)
        await theclient.send_message(message.channel, "<@" + message.author.id + "> " + l['joke'])

    if message.content.startswith('!et_as'):
        if Feast == True and FeastActive == False:

            Feast = False
            FeastActive = True
            await theclient.send_message(message.channel, "<@" + message.author.id + "> has begun a feast! Hurry, 10 seconds!")
            time2.sleep(10)
            FeastActive = False
            await theclient.send_message(message.channel, "@everyone We have feasted on " + str(FeastCount) +" as! Next feast can start in 3 hours")
            time2.sleep(10800)
            Feast = True

1 个答案:

答案 0 :(得分:0)

您需要在事件之外设置全局变量

FeastActive = False
Feast = True
FeastCount = 0

@theclient.event
async def on_message(message):
  global FeastActive
  global Feast
  global FeastCount        
  #rest of your code

这是对我有用的完整代码

@theclient.event
async def on_message(message):
  global FeastActive
  global Feast
  global FeastCount

  if message.author == theclient.user:
    return

  if FeastActive == True: 
    FeastCount += 1
    await theclient.send_message(message.channel, ' NOM NOM NOM')

  if message.content.startswith('!hello'):
    msg = 'Hello {0.author.mention}'.format(message)
    await theclient.send_message(message.channel, msg)

  if message.content.startswith('!joke'):
    r = requests.get('https://icanhazdadjoke.com', headers={"Accept":"application/json"}).text
    l = json.loads(r)
    await theclient.send_message(message.channel, "<@" + message.author.id + "> " + l['joke'])

  if message.content.startswith('!et_as'):
    if Feast == True and FeastActive == False:

      Feast = False
      FeastActive = True
      await theclient.send_message(message.channel, "<@" + message.author.id + "> has begun a feast! Hurry, 10 seconds!")
      await asyncio.sleep(10)
      FeastActive = False
      await theclient.send_message(message.channel, "@everyone We have feasted on " + str(FeastCount) +" as! Next feast can start in 3 hours")
      await asyncio.sleep(5)
      Feast = True