-1
global t
t = 0
@bot.command()
async def ping(ctx, member: discord.Member):
  while True:
    await ctx.channel.send(member.mention)
    @bot.event
    async def on_message(message):
      try:
        if message.author == member:
          t = 5     #(A)
          return
      except:
        pass
    if t == 5:
      break

Line (A) shows an error. I assumed the problem was that the variable t was not carrying through the @bot.event, but it seems like even the global command does not work. Is there some other problem that I just don't see?

  • Does this answer your question? [Use of "global" keyword in Python](https://stackoverflow.com/questions/4693120/use-of-global-keyword-in-python) – TheFungusAmongUs Jul 26 '22 at 04:28

1 Answers1

0

Explanation

When defining t, you are already defining it at the module (global) level. Thus, the global t command is redundant.

Instead, you should use global inside each new local scope you want to use t in.

As of now, the statement t = 5 creates a variable local to on_message. You probably want to edit the global t, which can be accomplished with the following edits to your code:

Code

t = 0
@bot.command()
async def ping(ctx, member: discord.Member):
  while True:
    await ctx.channel.send(member.mention)
    @bot.event
    async def on_message(message):
      global t  # Since we are assigning t in this function, we must state to use t from the global scope
      try:
        if message.author == member:
          t = 5     #(A)
          return
      except:
        pass
    if t == 5:
      break

Reference

Scopes and namespaces

TheFungusAmongUs
  • 1,423
  • 3
  • 11
  • 28