【问题标题】:Counting discord bot python计数不和谐机器人python
【发布时间】:2021-07-13 09:45:19
【问题描述】:

我查看了其他代码并没有弄清楚,我想要的是每当发送数字时都会发送消息,每次发送所述数字时,数字都会增加一。这是我的代码:

 counter = 0

if message.channel.startswith(counter):
    await message.channel.send(‘test, this will be changed later’)
    counter +=1```

【问题讨论】:

  • 嗨,这是您正在尝试构建的聊天机器人吗?
  • 怎么了?请提供错误或与预期不同的情况。
  • 没有发生错误,机器人回复我说“1”(之前没有),但仍然没有为我说 2、3 或任何一个做任何事情。哦,是的,我也将 counter = 0 更改为 counter = 1

标签: python count discord bots


【解决方案1】:

您可能需要先转换为字符串......

counter = 0

if message.channel.startswith(str(counter)):
    await message.channel.send("test, this will be changed later")
    counter += 1

【讨论】:

  • 可悲的是没有做任何事情
【解决方案2】:

这会给频道带来什么?

counter = 0

await channel.send(f'Start waiting for counter: {counter}')

if message.channel.startswith(str(counter)):
    counter += 1
    await channel.send(f'waiting for new counter: {counter}')

【讨论】:

    【解决方案3】:

    好的,现在我知道你的问题是什么了。您正在使用 discord.py 并且每次编写消息时都会触发事件 onMessage ,因此您每次创建一个名为“counter”的新变量,其值为 0,然后将其增加到 1,但 counter int 永远不会保存。对此的修复是某种数据源。您可以尝试每次保存号码,例如在一个 txt 文件中。这应该使它工作(代码):

    counter = 0
    
    # What the Message should start with
    if message.content.startswith('Text'):
        # Try to read the file, if it is not existing create it with 0 as number in it.
        try:
            f = open("counter.txt", "r")
            # Set the content of the text file as counter int
            counter = int(f.readline())
        except:
            f = open("counter.txt", "a")
            f.write(str(0))
    
        # Add a Number to the Counter
        counter += 1
        # Overwrite the current Number with the New Number
        f = open("counter.txt", "w")
        f.write(str(counter))
    
        # Send a Message with a certain String (Test! in this case and the Int 
        # that got counted up)
        await message.channel.send('Test! ' + str(counter))
    

    【讨论】:

    • 很好,但是无论我执行什么命令,即使它只是对消息的简单响应,我总是在 if 语句的末尾收到此错误:Unndent 与任何其他命令不匹配缩进级别
    • 会不会是你的 def 函数不是异步的?您可能需要在函数前添加async,并且在发送消息时需要在其前添加await
    • 我很确定它是异步的,我的代码与您所说的相符
    • 刚刚发现错误,我的代码中的一行是一个空格,这在 30 行之后才把我的代码弄乱了,奇怪
    【解决方案4】:

    += 在 Python 中不起作用,请改用“var = var + 1”

    【讨论】:

    猜你喜欢
    • 2021-10-30
    • 2021-05-27
    • 2021-07-15
    • 2017-05-31
    • 2021-03-29
    • 2021-07-11
    • 2021-03-25
    • 2018-08-13
    • 1970-01-01
    相关资源
    最近更新 更多