Discord机器人发送随机消息



我想制作一个discord bot,它每24小时向指定的通道发送一条消息列表中的随机消息。在python中我该如何做到这一点?

您可以为discord bot使用aiocron来将消息调度到特定通道。

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

您需要一个包含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)

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

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

导入时间模块,永远重复,秒等1天,打印hello world。其中的一个问题是电脑全天候运行。我真的想不出解决这个问题的办法,但如果你想要简单,你可以这样做。

对于discord代码,请使用示例quickstart。要开始,请转到此处进行申请。使用discordapi引用来解决其他问题。请务必查找任何您感到困惑的内容。

最新更新