python - 尝试每小时向频道发送消息
问题描述
我正在尝试创建一个简单的 Discord 机器人,它每小时向频道发送一条消息,当我在终端中对其进行测试时,它工作正常,每 2 秒打印一次“测试”。但是当我想添加'await bot.channel.send('here')'行时,它只在终端打印'test'一次,而在discord频道中什么也没有
import discord,asyncio,os
from discord.ext import commands, tasks
token = 'xxx'
bot = commands.Bot(command_prefix='.')
@bot.event
async def on_ready():
change_status.start()
print('bot in active')
@tasks.loop(seconds=2)
async def change_status():
channel = bot.get_channel = xxx
await bot.change_presence(activity=discord.Game('online'))
print('test')
await bot.channel.send('here')
bot.run(token)
解决方案
您正在做以下错误:
channel = bot.get_channel = xxx
问题是 bot.get_channel 是一个函数。这意味着您实际上需要执行以下操作:
channel = bot.get_channel(xxx)
出错的原因是您没有正确执行 bot.get_channel() 函数。这样channel的值就变成了xxx。但是为了向通道发送消息,您需要通道对象。您只能通过正确执行该功能来获得它。
所以如果你这样做了:
channel = bot.get_channel(id)
await channel.send('Your message')
然后 bot.get_channel(id) 返回一个通道对象,您可以将其分配给变量通道。您稍后可以使用它向该频道发送消息。
另外需要注意的是 bot.channel 与 channel 变量不同。因此,如果您在通道中有一个通道对象。您不能使用 bot.channel.send() 发送内容。你需要做channel.send()。
推荐阅读
- c# - 如何使用 webclient 将大数据上传到主机
- batch-file - 为什么不能编译批处理文件?
- azure - Powershell / Azure Functions - 根本不运行
- javascript - 位于组件中的 AngularJS 元素仅在第二次单击后才会触发
- vhdl - VHDL:端口什么时候可以用作信号?
- python - 重用中间层作为 Keras 中另一个模型的输入
- javascript - 如何在画布中绘制两个具有样式的图像?
- xtext - 在 IBM RSA 9.6.1 上安装 Xtext
- google-apps-script - 表单提交触发器已过期?
- phpstorm - 默认情况下 PhpStorm 流利的设置器