【问题标题】:How to send message with discord.py bot from another python file?如何使用 discord.py bot 从另一个 python 文件发送消息?
【发布时间】:2022-01-04 21:13:41
【问题描述】:

这是我的代码的骨架版本:

bot.py

import discord

client = discord.Client()

async def send_notification(notification):#this method is tested and works when called from same file
    for guild in client.guilds:
        for channel in guild.text_channels:
            if channel.name == CHANNEL_NAME:
                await channel.sent(notification)

def start_bot():
    client.run(TOKEN)

def notification(notification):
    asyncio.create_task(send_notification(notification))#likely error here

ma​​in.py

import bot
from time import sleep

def main():
  bot.start_bot()
  sleep(10)
  bot.notification('some notification')

main()

您好,我正在尝试从不同的 python 文件向所有行会发送消息。我知道我在处理异步任务的方式上犯了一些基本错误。目前 ma​​in.py 甚至没有到达 sleep() 语句。

  1. 有没有办法从 ma​​in.py 引用 client 以便可以使用它调用方法
  2. 我可以创建一些 api 以便任何 python 文件都可以访问机器人内部的方法

提前致谢。

【问题讨论】:

    标签: python asynchronous discord.py


    【解决方案1】:

    找到解决方法。更多地查看 discord.py 的文档,很明显它喜欢成为自己独立的东西,这就是为什么我从其他文件中引用它的方法并不理想。我最终不断地从 json 文件中读取:

    async def update_notifications():
        while True:
            with open(JSON_PATH, 'r') as file:# extract all content from json file
                content = json.load(file)
            while len(content['notifications']) > 0:# send all notifications one by one
                await send_notification(content['notifications'][0])
                content['notifications'].pop(0)
            with open(JSON_PATH, 'w') as file:# write the now empty content back to json file
                json.dump(content, file, indent=4)
            await asyncio.sleep(20)# sleep in seconds
    

    json 文件的结构如下:

    {
        "notifications":["notification1","notification2",...]
    }
    

    为了触发协程update_notifications(),创建了一个循环on_ready

    @client.event
    async def on_ready():
        client.loop.create_task(update_notifications())
    

    这种方法的优点是任何 python 脚本,甚至其他语言都可以通过写入 json 文件来告诉机器人发送通知。

    【讨论】:

      【解决方案2】:

      client.run(TOKEN) 阻止主线程的执行,因为它启动了一个异步事件循环。如果你想在机器人启动后只运行一个任务,你可以使用机器人的on_ready处理程序:

      import discord
      
      client = discord.Client()
      
      CHANNEL_NAME = "some-channel"
      
      @client.event
      async def on_ready():
          for guild in client.guilds:
              for channel in guild.text_channels:
                  if channel.name == CHANNEL_NAME:
                      await channel.send("hello world!")
      
      client.run('your token here')
      

      见:https://discordpy.readthedocs.io/en/stable/quickstart.html

      回答您的 2 个问题:

      1. bot.client 应该这样做,但是在制作 Discord 机器人时,您正在做的是一种反模式。最好坚持文档。但是,您可以使用继承对您的机器人进行子类化,但这有点高级。
      2. 您已经可以访问机器人方法。见上文。

      【讨论】:

        猜你喜欢
        • 2022-11-25
        • 1970-01-01
        • 2021-11-29
        • 2021-03-08
        • 2022-01-21
        • 2021-02-24
        • 2021-03-11
        • 2021-09-15
        • 1970-01-01
        相关资源
        最近更新 更多