【问题标题】:Python 3 Discord Bot Function Add To ItselfPython 3 Discord Bot 函数添加到自身
【发布时间】:2020-05-05 13:32:24
【问题描述】:

您好,我正在尝试为 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))

这确实有点用,我不能让它在聊天中说出来“类型错误:对象方法不能用于'await'表达式”,它也不会根据用户是谁而改变命令是

【问题讨论】:

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


    【解决方案1】:

    你的问题在于你的 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
    

    【讨论】:

    • 非常感谢,我只是有一个附带问题,为什么代码间隔多远很重要,因为当我粘贴您发送给我的内容时,它不起作用但是当我移动它并排成一行时它成功了,你将如何制作它,所以它是每个用户的不同计数器
    • 这些是很多不同的问题,答案相当复杂。以下是简短版本: 1. 是的,代码间隔多远确实很重要。 Python 使用换行符和制表符而不是花括号。 2. 您需要为每个用户创建一个单独的文件,但此时我建议使用 SQLlite 之类的数据库。
    猜你喜欢
    • 2019-04-20
    • 2019-09-05
    • 2019-07-21
    • 2021-05-17
    • 2021-07-18
    • 2021-04-29
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    相关资源
    最近更新 更多