【问题标题】:Get Complete Servers List获取完整的服务器列表
【发布时间】:2018-11-09 23:36:34
【问题描述】:

那么如何获取我的机器人已连接或安装的所有服务器列表。我使用了下面的代码,但现在不知道为什么。

servers = list(bot.servers)
print("Connected on " + str(len(bot.servers)) + "servers:")
for x in range(len(servers)):
    print('  ' + servers[x-1].name)

我的bot.py完整代码

token = "This is my Token" # This is what the bot uses to log into Discord.
prefix = "?" # This will be used at the start of commands.

import discord
from discord.ext import commands
from discord.ext.commands import Bot

bot = commands.Bot(command_prefix=prefix)
bot.remove_command("help")

@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print(discord.__version__)
    print('------')

@bot.command(pass_context=True)
async def ping(ctx):
    msg = 'Pong {0.author.mention}'.format(ctx.message)
    await bot.say(msg)

@bot.command(pass_context=True)
async def hello(ctx):
    msg = 'hello... {0.author.mention}'.format(ctx.message)
    await bot.say(msg)

bot.run(token)

【问题讨论】:

  • 如果你说它是如何不工作的,那会很有帮助。你得到错误的输出吗?完全没有输出?您收到错误消息吗?
  • 另外,for server in servers: print(' ' + server) 更 Pythonic。
  • 似乎服务器不是命令的属性。Bot 类:discordpy.readthedocs.io/en/rewrite/ext/commands/api.html#bot

标签: python python-3.x discord discord.py


【解决方案1】:

对于async 分支,bot.servers 返回机器人可以看到的所有服务器的可迭代对象。

对于rewrite 分支,server 已重命名为guild,因此请改用bot.guilds。

您可以修改您的on_ready 事件以打印出所有服务器名称。

异步

@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print(discord.__version__)
    print('------')

    print('Servers connected to:')
    for server in bot.servers:
        print(server.name)

重写

@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print(discord.__version__)
    print('------')

    print('Servers connected to:')
    for guild in bot.guilds:
        print(guild.name)

【讨论】:

  • 谢谢兄弟,它的工作是否可以获取服务器 ID 和服务器名称?
  • nvm 把它改成了 print(server.name) 到 print(server.id) 它工作了
  • 很高兴它的工作!为了将来参考,这里是您可以访问的server 类的属性:discordpy.readthedocs.io/en/latest/api.html#server
  • 它太老了
  • @BlackThunder 更新为包含rewrite 分支代码和文档
【解决方案2】:

我对代码有一点乐趣。这是当前工作的版本。

@bot.event
async def on_ready():
print(f'Currently at {len(bot.guilds)} servers!')
print('Servers connected to:')
print('')
for server in bot.guilds:
    print(server.name)

这对你应该没问题。

【讨论】:

    猜你喜欢
    • 2020-03-27
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    • 2018-07-24
    • 1970-01-01
    相关资源
    最近更新 更多