【问题标题】:Discord bot sending random messagesDiscord 机器人发送随机消息
【发布时间】:2021-08-19 05:34:16
【问题描述】:

我想制作一个不和谐的机器人,它每 24 小时从消息列表中向指定的频道发送一条随机消息。我将如何在 python 中执行此操作?

【问题讨论】:

    标签: python discord


    【解决方案1】:

    我要做的第一件事是查看discord api quickstart 以了解如何开始使用机器人。然后对于 24 小时的部分,它变得有点困难。例如,如果您想每 24 小时打印一次“hello world”,您可以使用此代码。

    import time 
    while True:
       time.sleep(86400)
       print(“hello world”)
    

    导入时间模块,永远重复,以秒为单位等待1天,打印hello world。这样做的一个问题是计算机是 24/7 全天候运行的。我真的想不出一个解决办法,但如果你想要简单,你可以这样做。

    对于不和谐的代码,请使用示例快速入门。开始去here申请。使用 discord api 参考来解决其他所有问题。确保查找您感到困惑的任何内容。

    【讨论】:

      【解决方案2】:

      您可以使用aiocron 让 discord 机器人将消息安排到特定频道。

      我做了一些类似的事情,这是我用来随机向频道发送消息的代码。

      您将需要一个包含您的 discord 令牌的 token.txt 文件和一个带有频道 ID 的 channel.txt。

      import discord
      import aiocron
      import random
      
      TOKEN = open("token.txt","r").readline()
      
      random_messages = ['list', 'of', 'random', 'messages', 'foo', 'bar']
      
      # this will run at 4:00 AM of the server time every day
      # follows the logic of normal cron
      
      @aiocron.crontab('00 4 * * *')
      async def cronjob():
          # reads the channel ID from a channel.txt file
          CHANNEL_ID = open("channel.txt","r").readline()
          # sets the channel info
          channel = client.get_channel(int(CHANNEL_ID))
          # uses the random library to select a message from the list
          message = random_messages[random.randrange(0, len(random_messages))]
          # sends the random message
          await channel.send(message)
      
      client.run(TOKEN)
      

      【讨论】:

        猜你喜欢
        • 2021-08-27
        • 2021-06-05
        • 2021-01-08
        • 2019-06-13
        • 2021-02-22
        • 2020-11-23
        • 2019-09-12
        • 2022-01-03
        • 2019-09-16
        相关资源
        最近更新 更多