gpt4 book ai didi

Python Discord.py Bot 间隔消息发送

转载 作者:行者123 更新时间:2023-12-04 17:29:03 46 4
gpt4 key购买 nike

我一直在尝试使用 discord.py 库为 Discord 创建一个机器人,但是当我运行该程序时,它没有按预期发送消息。这是一个简单的机器人,假设每 10 分钟向 channel 发送一条消息。我在命令行中没有收到任何错误消息并且似乎看不到任何明显的错误?任何帮助将不胜感激。

import asyncio

client = discord.Client()

async def my_background_task():
await client.wait_until_ready()
counter = 0
channel = discord.Object(id='my channel ID goes here')
while not client.is_closed:
counter += 1
await message.channel.send("TEST")
await asyncio.sleep(5) # task runs every 60 seconds

@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')

client.loop.create_task(my_background_task())
client.run('My token goes here')

最佳答案

虽然创建任务可以工作,但如果有更好的选择,我不会推荐它。 Dpy 的 command.ext 插件有一个直接内置的基于任务的系统,所以让我们研究一下使用它。

import discord
from discord.ext import tasks

client = discord.Client()

@tasks.loop(minutes=10)
async def my_background_task():
"""A background task that gets invoked every 10 minutes."""
channel = client.get_channel(754904403710050375) # Get the channel, the id has to be an int
await channel.send('TEST!')

@my_background_task.before_loop
async def my_background_task_before_loop():
await client.wait_until_ready()

my_background_task.start()
client.run('Your token goes here')
上述循环运行的时间取决于人类心理、能量和宇宙法则。
那是:
• 你厌倦了
• 断电,您的脚本停止工作
• 宇宙爆炸
在此处阅读更多相关信息:
  • https://discordpy.readthedocs.io/en/latest/ext/tasks/
  • 关于Python Discord.py Bot 间隔消息发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61366148/

    46 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com