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

2024-05-05 09:51:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个不和谐的bot,用户可以分配某些语音频道,以使bot在用户加入语音频道时自动加入语音频道

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

我已经编写了一段代码将其保存到.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,在频道周围设置str()也不起作用

有没有办法让我做到这一点


Tags: 文件代码用户txt数据库列表savebot
1条回答
网友
1楼 · 发布于 2024-05-05 09:51:25

您可以像这样使用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)

相关问题 更多 >