如何使机器人状态显示机器人正在与之玩的所有成员?

2024-04-19 03:48:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正试图在discord python rewrite中为我的discord bot生成一个状态循环命令。我已经发出了status命令,但是让status显示bot所在的所有服务器中的所有用户的数量是不起作用的。当我尝试打印代码时,它工作得很好。当我尝试将其作为一种状态运行时,我始终显示与0个成员一起玩。我不知道如何解决这个问题

代码:

from discord.ext import commands, tasks
import asyncio
import os
import random
from itertools import cycle

client = commands.Bot(command_prefix = '?')
status = cycle(["?help", "Welcoming People", f"Playing with {len(set(client.users))} users"])

@client.remove_command('help')

@client.event
async def on_ready():
    change_status.start()
    print ('Bot online')
    print (f"Playing with {len(client.users)} users")

@tasks.loop(seconds=10)
async def change_status():
    await client.change_presence(status=discord.Status.idle, activity=discord.Game(next(status)))```

Tags: 代码fromimport命令client状态botstatus
1条回答
网友
1楼 · 发布于 2024-04-19 03:48:57

它不能按预期工作的原因如下:

status = cycle(["?help", "Welcoming People", f"Playing with {len(set(client.users))} users"])

我们用一个没有更新的数组启动一个循环。为了解释,让我们键入它(我们感兴趣的字符串):

f"Playing with {len(set(client.users))} users"

在创建字符串的那一刻,我们在那一刻输入值。这就变成了:

"Playing with 0 users"

这将在阵列周期保持时使用。因为cycle只知道这个字符串,所以它将只使用这个字符串。 如果要更新字符串,必须手动更改字符串,并在每次需要时进行更新

我建议您创建自己的循环变体。它会更新字符串。一种方法是:

last_string = 0
@tasks.loop(seconds=10)
async def change_status():
    # Update the member count string
    list[str_member_index] = f"Playing with {len(set(client.users))} users"
    status_str = list[last_string]

    await client.change_presence(status=discord.Status.idle, activity=discord.Game(status_str))

    last_string += 1
    if last_string == len(list):
        last_string = 0

此代码不完整,因为您仍然需要分配str_member_index例如。但它会在你的状态中循环。并更新成员计数状态

相关问题 更多 >