【问题标题】:How to run discord.py interactively in jupyter notebook?如何在 jupyter notebook 中交互式运行 discord.py?
【发布时间】:2021-10-29 11:15:29
【问题描述】:

在discord.py中,你可以初始化一个Client,然后用client.run()运行它。但函数永远不会返回。

如果我只想检索一些消息历史然后在 jupyter notebook 中使用它怎么办?

@bot.command()  
async def history(ctx):
    counter = 0
    messageList=[]
    async for message in ctx.channel.history(limit = 100):
        print(message.author, message.content)
        counter += 1
        messageList.append(message)

    await ctx.send(f'total **{counter}** messages in this channel.')

    # How to return the messageList to my jupyter notebook cell and I start playing with the messageList?

如何返回messageList?

【问题讨论】:

  • 我不确定您的意图,您是否要启动机器人然后运行命令并终止机器人(您的代码所描述的内容);或启动机器人,然后在启动时自动获取某个特定频道的频道历史记录并终止机器人(您在描述什么)?
  • 我只想返回列表,但是函数 client.run() 和 bot.run() 永远不会返回
  • 是的,我知道那部分,但请回答我之前评论中的问题,以进一步帮助您。
  • 你说的两种方式都可以,我就是想要返回列表

标签: python jupyter-notebook discord discord.py pycord


【解决方案1】:

没有很好的方法来做到这一点。 discord.py 旨在启动一次并运行直到程序终止,因为所有内部对象都会在机器人关闭时被销毁,这使得再次启动机器人备份几乎是不可能的。并且不可能“暂停” discord.py 并运行您的代码,然后再恢复 discord.py,因为 Discord API 通过 Web 套接字进行通信,这依赖于持续不断的心跳和确认流。

一种可能的解决方法是:

  • 在代码中使用单个事件循环。
  • 使用loop.run_until_complete() 启动机器人的内部循环。
  • 每次需要运行机器人时创建一个新的Client。
  • 创建一个用于获取信息的on_ready 事件句柄。
  • 缺点是您将无法与Message 对象进行交互(即删除、编辑等),它们只能被查看。

例子:

import asyncio
import discord

TOKEN = "YOURBOTTOKEN"
loop = asyncio.get_event_loop()


def get_message_list(token, channel_id):
    client = discord.Client(loop=loop)
    message_list = []

    @client.event
    async def on_ready():
        nonlocal message_list
        channel = client.get_channel(channel_id)
        if not channel:  # incase the channel cache isn't fully populated yet
            channel = await client.fetch_channel(channel_id)

        async for message in channel.history(limit=100):
            message_list.append(message)
        await client.close()

    async def runner():
        try:
            await client.start(token)
        finally:
            if not client.is_closed():
                # Incase the bot was terminated abruptly (ie. KeyboardInterrupt)
                await client.close()

    loop.run_until_complete(runner())
    return message_list


message_list = get_message_list(TOKEN, channel_id=747699344911712345)
print("Message list for channel #1:", message_list)

# ... do stuff with message_list

message_list = get_message_list(TOKEN, channel_id=747699344911754321)
print("Message list for channel #2:", message_list)

# ... do more stuff with message_list

# Finally closes the event loop when everything's done
loop.close()

我建议您不要这样做,而是为您要完成的任务找到另一种解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 2019-11-14
    • 2018-11-18
    • 1970-01-01
    • 2019-07-22
    相关资源
    最近更新 更多