我想创建一个Python Bot,该Bot跟踪用户在服务器上处于语音状态所花费的时间以创建排名系统。不幸的是,我不知道如何更新guild.members列表,因此也不能更新member.voice值。 我尝试做一个while循环,但是列表似乎没有更新。 非常感谢您的帮助。
# bot.py
import os
import asyncio
import discord
import random
import datetime
from discord.utils import get
import time
from dotenv import load_dotenv
from discord.ext import tasks
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
client = discord.Client()
@client.event
async def on_ready():
print("Bot is ready")
while True:
time.sleep(2)
guild = discord.utils.find(lambda g: g.name == GUILD, client.guilds)
for m in guild.members:
print(m.voice)
time.sleep(2)
client.run(TOKEN)
答案 0 :(得分:0)
您可以使用on_voice_state_update()
事件来跟踪连接或断开语音通道的每个成员。确保使用discord.ext.commands
客户端对象。
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='$')
@client.event
async def on_voice_state_update(member, before, after):
if not before.channel and after.channel:
await start_tracking(member) #your method that tracks the time
#Remember that it has to be a coroutine
if before.channel and not after.channel:
await stop_tracking(member)
编辑:请不要在异步脚本中使用time.sleep()
。使用asyncio
进行睡眠和循环之类的操作