【问题标题】:Discord.py how can I get the Voice channel ID of a user AND save it to a .txt file?Discord.py 如何获取用户的语音频道 ID 并将其保存到 .txt 文件?
【发布时间】:2021-08-05 23:05:15
【问题描述】:

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

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

我已经写了一个代码来保存到一个.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() 也不起作用。

有什么办法可以做到吗?

【问题讨论】:

    标签: python discord discord.py


    【解决方案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)
    

    【讨论】:

    • 我不知道我可以使用 .id 作为频道的 ID。无论如何,非常感谢!
    猜你喜欢
    • 2021-11-13
    • 2019-11-23
    • 1970-01-01
    • 2021-07-21
    • 2022-01-16
    • 1970-01-01
    • 2020-12-21
    • 2022-07-06
    • 1970-01-01
    相关资源
    最近更新 更多