不和谐.py为会话添加超时

2024-03-28 14:49:07 发布

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

如何为用户创建的会话添加超时,并在达到x时间量时自动结束会话并将其从会话列表中删除?你知道吗

当用户键入!ses时,bot将为该用户创建会话。你知道吗

import discord


class Session:
    def __init__(self, author, channel):
        self.author = author
        self.channel = channel

    def get_author_id(self):
        return self.author.id


class SessionTest(discord.Client):

    def __init__(self, **options):
        self.sessions = list()
        super().__init__(**options)

    async def on_ready(self):
        print('Bot ready.')

    async def on_message(self, message):
        if "!ses" in message.content:
            if any(s.get_author_id() == message.author.id for s in self.sessions):
                await message.channel.send("Session already exists.")
            else:
                session = Session(message.author, message.channel)
                msg = format("Session created for %s" % message.author.name)
                await message.channel.send(msg)
                self.sessions.append(session)
        elif "!dos" in message.content:
            ses = next((s for s in self.sessions if s.get_author_id() == message.author.id), None)
            if ses is not None:
                msg = format("Done something for %s" % message.author.name)
                await message.channel.send(msg)
            else:
                await message.channel.send("You don't have a session yet.")


client = SessionTest()
client.run("", bot=True)

Tags: inselfsendidmessageforifsession
1条回答
网友
1楼 · 发布于 2024-03-28 14:49:07

您只需要在适当的时间内添加一个^{},然后就可以删除会话了。你知道吗

async def on_message(self, message):
    if "!ses" in message.content:
        if any(s.get_author_id() == message.author.id for s in self.sessions):
            await message.channel.send("Session already exists.")
        else:
            session = Session(message.author, message.channel)
            msg = format("Session created for %s" % message.author.name)
            await message.channel.send(msg)
            self.sessions.append(session)
            await asyncio.sleep(60)  # One minute
            self.sessions = [s for s in self.sessions if s.get_author_id() != message.author.id]
    elif "!dos" in message.content:
        ses = next((s for s in self.sessions if s.get_author_id() == message.author.id), None)
        if ses is not None:
            msg = format("Done something for %s" % message.author.name)
            await message.channel.send(msg)
        else:
            await message.channel.send("You don't have a session yet.")

相关问题 更多 >