Discord.py 如何获取用户的语音通道 ID 并将其保存到 .txt 文件?

时间:2021-05-16 12:55:44

标签: python discord discord.py

我正在尝试制作一个 Discord 机器人,用户可以分配某些语音频道,让机器人在用户加入时自动加入语音频道。

但是,我需要制作类似数据库的东西来保存分配的语音频道列表作为自动加入频道,以防止在机器人关闭时分配的频道列表丢失。< /p>

我写了一段代码把它保存到一个.txt文件中,代码是:

@bot.command()
async def assign(ctx):
        channel = ctx.author.voice.channel
        save = open('C:\Discordbots\channels_database.txt','w')
        save.write(channel)

但是,当我运行它时,出现如下错误:

discord.ext.commands.errors.CommandInvokeError:
Command raised an exception: TypeError: write() argument must be str, not VoiceChannel

我不知道如何将语音频道 ID 转换为 str,并且在 channel 周围使用 str() 也不起作用。

有什么办法可以做到这一点吗??

1 个答案:

答案 0 :(得分:1)

您可以像这样使用 ctx.author.voice.channel.name

channel = ctx.author.voice.channel.name

ctx.author.voice.channel.id(即使您更改频道名称也一样):

channel = str(ctx.author.voice.channel.id)

同样好的做法是使用 with,因此我建议将您的代码更改为:

@bot.command()
async def assign(ctx):
    channel = ctx.author.voice.channel.name
    with open("C:\Discordbots\channels_database.txt", "w") as f:
        f.write(channel)