Python 3 Discord Bot 功能添加到自己

Python 3 Discord Bot Function Add To Itself

你好,我正在尝试为 discord bot 创建一个命令,这样当我输入 .count 时它会显示 +1 但如果我再次输入它会显示 +2 如果我再次输入它会显示+3 等。如果有人知道该怎么做,请告诉我,谢谢,我已经尝试了很多方法,包括

COUNT = 0
def increment():
    global COUNT
    COUNT += 1
increment()

print(COUNT)

这没有用,只是保持 1

更新:刚试过

if "!counter" == message.content.lower():
        await message.channel.send
        def get_var_value(filename="store.dat"):
            with open(filename, "a+") as f:
                f.seek(0)
                val = int(f.read() or 0) + 1
                f.seek(0)
                f.truncate()
                f.write(str(val))
                return val
                your_counter = get_var_value()
                print("This script has been run {} times.".format(your_counter))

好吧,它本身有点工作,我不能让它在聊天中说出来 "Type Error: object method can't be used in 'await' expression" 也不会改变,具体取决于执行命令的用户是谁

你的问题出在你 await message.channel.send 现在您正在等待函数本身,但您必须向它传递一个参数,如下所示:

await message.channel.send(counter)

现在你写文件的方法似乎是个不错的主意,但我们可以简化这个过程:

if "!counter" == message.content.lower():
    # a try except statement so that we only read the file if it exists and has the correct value
    try: 
        with open("store.dat", "r") as f:
            counter = int(f.read()) # read in the file contents
    except (FileNotFoundError, ValueError):
        counter = 0 # if something goes wrong, we reset the counter

    counter += 1
    await message.channel.send(f"This command has been called {counter} times") # give feedback in the channel
    with open("store.dat", "w") as f:
        f.write(str(counter)) # write the contents back into the file