是否可以通过discord.py获取用户所在的文本通道

时间:2020-05-12 01:53:19

标签: python discord discord.py

我正在尝试创建一个日志记录机器人,用于将消息存储在文本文件中。但我希望它专注于一个特定的文本通道进行监视。有什么办法可以做到吗?

代码:

import discord
class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as', self.user)
    async def on_message(self, message):
        file = open("logs.txt", "a", encoding="utf-8")
        if message.author != self.user:
            file.write(str(message.author) + ": " + message.content + "\n\n")
        else:
            return
        file.close()
        if message.content == "!logs":
            file = open("logs.txt", encoding="utf-8")
            embed = discord.Embed(title="Logs in this channel", description="All Messages In This Channel")
            embed.add_field(name='logs', value=file.read())
            await message.channel.send(content=None, embed=embed)
            file.close()
        if message.content == "!deletelogs":
            with open("logs.txt", "w", encoding="utf-8"):
                pass
        if message.content == "!lockbothere":
            # Lock Bot To TextChannel
bot = MyClient()
bot.run("lolno")

1 个答案:

答案 0 :(得分:2)

您可以只检查消息通道并使用ID或名称。

如果您输入以下打印语句,您将看到这些值,然后可以根据需要添加条件语句。

print(f'message channel is {message.channel} id {message.channel.id} name {message.channel.name}')

message.channel将返回discord.channel.TextChannel对象(用于文本通道)

message.channel.id将返回频道ID的整数值

message.channel.name将返回频道名称的字符串值(例如“常规”)