重新连接到 discord.py 中的视图(带有按钮等)。

huangapple go评论70阅读模式
英文:

Reconnect to a view (with buttons etc.) in discord.py

问题

我正在使用我的discord.py机器人处理一个考勤列表。这是一个包含2个按钮的简单视图。这个视图需要连续运行7天,所以很重要的一点是我的机器人不能出现错误或崩溃。

在你停止机器人后,有没有办法重新连接到一个视图(包含按钮等内容)?原因是我的机器人还在执行其他任务,有时它们会出现问题,我不得不重新启动机器人,但这会导致考勤列表无法继续运行。

bot.run(config["TOKEN"], reconnect=True)

^ 对于断开连接或我重新启动路由器来说,这个方法运行得很好,但我还没有找到一种方法在重新启动整个机器人/脚本后重新连接到视图。

有什么想法吗?

英文:

I'm handling an attendance list with my discord.py bot. It's a simple view with 2 buttons. The view needs to run for 7 days straight, so its important that my bot doesn't bug/crash.

Is there a way to reconnect to a view (containing buttons and so on) after you stopped your bot? The reason is that my bot is doing other tasks as well and sometimes they bug out and I have to restart the bot, but this leads to the attendance lists being dead..

bot.run(config["TOKEN"], reconnect=True)

^ this is working fine for disconnects or me restarting my router, but I haven't found a solution to reconnect to the views after restarting the whole bot/script.

Any ideas?

答案1

得分: 2

如果您需要在机器人崩溃或重新启动后保存信息,那么您需要将这些信息保存在某种永久存储中,比如数据库或json文件。如果您想保持简单,可以将信息存储在json文件中,并让您的机器人读取/写入该文件,而不是将其全部处理在内存中。

关于视图部分,如果您只需要让视图重新启动,您可以在机器人启动时的某个地方添加这一行,比如"on_ready()",例如:

async def on_ready(self):
    self.add_view(MyView())

为了使其正常工作,很重要的一点是视图中的所有项目(如按钮)都需要分配一个唯一的ID给它们。例如:

@discord.ui.button(
    label='Admin Menu 📝',
    style=discord.ButtonStyle.grey,
    custom_id='admin_menu' # <-- 这个需要设置
)

如果您访问discord.py的GitHub页面,他们还有一个"examples"文件夹,在视图下有一个名为"persistence.py"的示例,展示了我在这里提到的内容的完整示例。

英文:

If you need to save information after the bot either crashes or is restarted then you will need to hold that information in some sort of permanent storage like a database or json file. If you want to keep it simple you can just store information in a json and have your bot read/write to that file instead of handling it all in memory.

Regarding the views, if you just need to get the view to start up again you can add this line to somewhere that is executed on your bot's start like "on_ready()" for example.

async def on_ready(self):
    self.add_view(MyView())

It is important for this to work that all the items (like buttons) in your view have a unique id given to them. For example:

    @discord.ui.button(
        label=&#39;Admin Menu &#128221;&#39;,
        style=discord.ButtonStyle.grey,
        custom_id=&#39;admin_menu&#39; # &lt;-- this needs to be set
    )

If you go to the github page for discord.py they also have an "examples" folder, under views they have a example called "persistence.py" that shows a full example of what I am mentioning here

huangapple
  • 本文由 发表于 2023年4月13日 18:22:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76004323.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定