python - 如何让机器人每 5 分钟或因为另一个事件发布/发送消息?
问题描述
我认为这将是一个简单的任务,但不知何故我什至可以把它搞砸。所以我只想让我的机器人每 5 分钟发送一条消息(以诱骗我的朋友)一条特定的消息。所以我发现这个不起作用或任何其他代码。我什至没有收到错误消息。所以我几乎一无所知,这很糟糕。
import discord
import asyncio
client = discord.Client()
async def my_background_task():
await client.wait_until_ready()
counter = 0
channel = discord.Object(id='channel_id_here')
while not client.is_closed:
counter += 1
await client.send_message(channel, counter)
await asyncio.sleep(60) # 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('token')
无论如何,这里是我的精简代码,没有所有的 Bot 命令。
import discord
from discord.ext.commands import Bot, has_permissions
import secrets
import numpy as np
import re
TOKEN = 'mytokenasastring'
BOT = Bot(command_prefix='!')
#... some commands for my bot for my friends and myself
BOT.loop.create_task(my_background_task())
BOT.run(TOKEN)
所以我只是像这样添加了上面的代码
async def my_background_task():
await BOT.wait_until_ready()
counter = 0
channel = discord.Object(id='mytestchannelidasastring') #i also tried as int but also doenst work
while not BOT.is_closed:
counter += 1
await BOT.send_message(channel, counter)
await asyncio.sleep(60) # task runs every 60 seconds
然后 vs 代码告诉我的 Bot 没有 send_message 方法。所以我将 send_message 的代码更改为此
await channel.send(counter)
但是现在我得到了警告/错误表单 VS 代码,该通道没有发送方法,所以我得到了(真实的?!)这样的通道
BOT.get_channel(id='mychannelidasstring')
它仍然不起作用,或者我没有收到任何类型的错误消息......请帮助,否则我会发疯的......
解决方案
尝试使用discord.tasks.loop
.
from discord.ext import tasks
counter = 0
@tasks.loop(minutes=1.0, count=None)
async def my_background_task():
global counter
channel = BOT.get_channel(123456789) # channel id as an int
counter += 1
await channel.send(f'{counter}')
my_background_task.start()
每分钟循环一次你的巨魔功能。
推荐阅读
- c++ - tex2D HLSL Shader Model 6.0 验证失败
- arrays - 在 ruby 中交换不同的数组元素
- php - 比较两次并在php中获得分钟小时的差异
- android - Android Kotlin - 从另一个 ViewModel 继承一个 VIewModel
- jquery - 如何在 jQuery 中创建画布并在多个区域中显示
- python - 在 Negative Sampling 中排除阳性样本
- windows - 启动提升单用户卸载程序的 Windows 10 中“应用程序和功能”的解决方法
- angularjs - 如何将 AngularJS 响应传递给 window.url
- java - 无法使用 JNDI 连接到 XA 数据源
- sql - 寻找转化率