自我解释,当我运行此命令时,即使我之前已将变量playercount分配为全局变量,也会出现标题中显示的错误。我在这里搞砸了是什么?
import discord
import asyncio
import mysql.connector
from discord.ext.commands import Bot
from discord.utils import get
mydb = mysql.connector.connect(
host='no',
database='no',
user='no',
password='no'
)
cursor = mydb.cursor()
client = Bot('!')
@client.event
async def on_ready():
print('===========')
print('Bot running')
print('===========')
global playercount
playercount = 0
@client.event
async def on_message(message):
if message.content == '?help':
helpMessage = discord.Embed(title="""Use ?joingame to join the game and follow instructions
given.""")
await message.channel.send(embed=helpMessage)
if message.content == '?joingame':
playercount = playercount + 1
player = message.author.id
add_player = "INSERT INTO user_info (userNum, UserId) VALUES (" + str(playercount) + ", " +
str(player) + ")"
cursor.execute(add_player)
next_player = "SELECT userNum FROM user_info"
cursor.execute(next_player)
numberPlay = cursor.fetchall()[0][0]
print(numberPlay)
playercount
是全局变量。这意味着从函数中只能读取它,而不能对其进行修改。更改方法是在函数内使用global
关键字。
关于为什么计数器总是重置为0的原因,这可能是因为在启动应用程序时,它会启动多个实例。因此,您需要将该值写入文件文本(txt或csv)或数据库中。
global playercount
playercount = 0
问题在于此行,因为变量在函数外部,因此不需要将其声明为全局变量删除该全局行并运行代码