Discord bot 发送随机消息

时间:2021-06-01 01:30:09

标签: python discord

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

2 个答案:

答案 0 :(得分:0)

我要做的第一件事是查看 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 参考来解决其他所有问题。请务必查找任何您感到困惑的内容。

答案 1 :(得分:0)

您可以使用 aiocron 为 Discord bot 安排消息到特定频道。

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

您需要一个包含您的不和谐令牌的 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)