【问题标题】:Making two bots count each other's messages让两个机器人互相计算对方的消息
【发布时间】:2021-09-17 14:27:08
【问题描述】:

所以,作为一个假期项目,我正在尝试制作两个回复对方消息的机器人。他们将检查发件人的 ID,如果它与其他机器人的 ID 匹配,它将发送一条消息,其中包含该机器人已回复的次数。

问题是当我尝试执行此操作时,两个机器人都发送两条消息,并且计数不高于 1。

这是我的代码:

import discord
import time

TOKEN = #BOT TOKEN#
client = discord.Client()


@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')


@client.event
async def on_message(message):
    if message.author == client.user:
        return
    tally = 0
    if message.author.id == 887901692673261618:
        tally += 1
        time.sleep(5)
        await message.channel.send(tally)


client.run(TOKEN)
    

我尝试在 TOKEN 和客户端定义下定义 tally 变量,但它随后显示在分配之前引用了 tally

【问题讨论】:

  • tally 在每次调用 on_message 时设置为 0。将此计数存储为全局变量,不要在此方法中将其设置为零?

标签: python discord bots


【解决方案1】:

在每条消息中,您都将计数变量设置为 0。这是在重置计数器,因此它不会增加

关于在赋值之前引用的变量,为了清楚起见,您应该在函数上方定义它。在 before client.run 的任何地方定义它都会起作用,但在 after client.run 中定义它不会起作用,因为 client.run 会阻止代码继续前进,除非机器人停止,所以你的变量是在您关闭机器人后而不是在它运行时定义的,因此会出现错误。现在

  • 您可以使用 global 关键字来修改在函数外部定义的变量的值
  • 你可以将tally设置为客户端的一个属性,这样就不需要使用全局关键字了

将其设置为client属性的示例

import discord
import time

TOKEN = #BOT TOKEN#
client = discord.Client()
client.tally = 0

@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')


@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.author.id == 887901692673261618:
        client.tally += 1
        time.sleep(5)
        await message.channel.send(client.tally)


client.run(TOKEN)

将其设置为全局变量的示例

import discord
import time

TOKEN = #BOT TOKEN#
client = discord.Client()
tally = 0

@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')


@client.event
async def on_message(message):
    global tally
    if message.author == client.user:
        return
    if message.author.id == 887901692673261618:
        tally += 1
        time.sleep(5)
        await message.channel.send(tally)


client.run(TOKEN)

考虑了解更多关于 python 中的变量作用域

【讨论】:

    猜你喜欢
    • 2021-04-09
    • 1970-01-01
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 2022-12-18
    • 2020-08-24
    相关资源
    最近更新 更多