【问题标题】:Disord.py - How to list all servers the bot is in?Disord.py - 如何列出机器人所在的所有服务器?
【发布时间】:2021-08-21 11:03:17
【问题描述】:

我正在尝试让我的机器人在上线时检查机器人所在的每台服务器并在目录中为它们创建一个文件夹,但我不断收到错误 list2 is not defined 即使 iv 已定义这是代码:

import discord
from discord.ext import commands
import os

PREFIX = "$"
bot = commands.Bot(command_prefix=PREFIX, description="Hi")

list1 = os.listdir('C:/Users/User/Desktop/BOT_FOLDER')
for guild in bot.guilds:
    print(guild.name)
    list2 = guild.name


print(os.listdir('C:/Users/User/Desktop/BOT_FOLDER'))

set1 = set(list1)
set2 = set(list2)

missing = list(sorted(set1 - set2))
added = list(sorted(set2 - set1))

print('missing:', missing)
print('added:', added)

newpath = r'C:\Users\User\Desktop\BOT_FOLDER\{}'.format(added)
if not os.path.exists(newpath):
    os.makedirs(newpath)

if os.path.exists("demofile.txt"):
  os.remove('C:/Users/User/Desktop/BOT_FOLDER/{}').format(missing)
else:
  print("The file does not exist")

bot.run('BOT_TOKEN_HERE')

【问题讨论】:

  • list2 是局部变量,仅在 for 循环内可见,使其成为全局变量

标签: python list directory discord discord.py


【解决方案1】:

其实翻译是对的!即使看起来不像,当您运行 set2 = set(list2) 时,list2 也没有定义。


为什么会这样

您基本上是在 bot 对象初始化之后立即调用 for guild in bot.guilds。但是,它还没有连接到 API,这意味着它还没有加载像 bot.guilds 这样的东西。该属性将是None,因此您的循环不会运行并且list2 不会被定义。


如何解决这个问题

等到您的机器人成功连接到 API,然后然后迭代您的公会。这可以通过使用on_ready() 事件来完成。此外,您需要将 .append() 项目添加到列表中,您不能只使用等号分配新项目。

@bot.event
async def on_ready():
    list1 = os.listdir('C:/Users/User/Desktop/BOT_FOLDER')
    list2 = []
    for guild in bot.guilds:
        print(guild.name)
        list2.append(guild.name)


    print(os.listdir('C:/Users/User/Desktop/BOT_FOLDER'))

    set1 = set(list1)
    set2 = set(list2)

    missing = list(sorted(set1 - set2))
    added = list(sorted(set2 - set1))

    print('missing:', missing)
    print('added:', added)

    newpath = r'C:\Users\User\Desktop\BOT_FOLDER\{}'.format(added)
    if not os.path.exists(newpath):
        os.makedirs(newpath)

    if os.path.exists("demofile.txt"):
        os.remove('C:/Users/User/Desktop/BOT_FOLDER/{}').format(missing)
    else:
        print("The file does not exist")

【讨论】:

    猜你喜欢
    • 2021-04-21
    • 1970-01-01
    • 2020-08-17
    • 2021-07-09
    • 2021-02-13
    • 2020-06-26
    • 2021-09-24
    • 2021-02-02
    • 2020-10-17
    相关资源
    最近更新 更多