新程序员在语音频道中 discord.py 至 return 数量的成员中设置不和谐机器人时遇到问题

New programmer having trouble setting up a discord bot in discord.py to return amount of members in a voice channel

我是一名新开发人员,一直在尝试制作一个 discord 机器人,它会对 discord 命令做出反应,以查看该命令来自(作者)的语音频道中有多少人,然后它会选择根据其中的人数从列表中随机选择一个游戏。我删除并重写了一堆东西,我很困惑。非常感谢您抽出宝贵时间,我对如何设置这些功能感到非常迷茫。

我正在使用 replit

import discord
import os
import requests
import json
import random


client = discord.Client()

game_list = ["League of Legends", "Valorant", "Valheim", "Apex Legends", "Tarkov", "Age of Empires", "Halo", "CSGO", "Seige" ]

print(random.choice(game_list))

def get_game():
  return(random.choice(game_list))



@client.event
async def on_ready():
  print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
  if message.author == client.user:
    return
 
  voice_channel = message.author.voice.channel

  msg = message.content
  
  def game_plz():
    return(voice_channel.members())
  
  if msg.startswith('!game'):
    await message.channel.send(get_game())

  if msg.startswith('!plz'):
    await message.channel.send(game_plz())




#@client.event

#async def 
#channel = client.get_channel()
#members = channel.members()
#memids = []
#for member in members:
#  meids.append(member.id)
#print(meids)

client.run(os.environ['token'])

discord.VoiceChannel.members is a list of discord.Member objects, you can check how many of these are within the list by using len。另请注意,channel.members 本身不是一个函数,您不需要包含 ()。请查看下面修改后的代码片段,以及任何进一步的解释。

# I'm suggest putting this outside of the on_message event
def game_plz(channel:discord.VoiceChannel):
    members = channel.members #finds members connected to the channel
    # channel.members is a list of discord.Member objects
    return len(members) # returns amount of members in the channel

# within your on_message event
    voice_channel = message.author.voice.channel
    msg = message.content

    if msg.startswith('!plz'):
        await message.channel.send(game_plz(voice_channel))
        # pass voice_channel as an argument into game_plz
        # voice_channel should be a discord.VoiceChannel object

其他链接:

  • Getting a list of all of the members in a specific voice channel - Whosebug
  • Retrieve list of members in channel - Whosebug
  • - Whosebug