python - 用 Python 编写 Discord 机器人 - 如何让它自动发送消息?
问题描述
我想让我的机器人每十分钟自动将图像发送到一个频道。这是我的代码:
def job():
channel = client.get_channel(803842308139253760)
channel.send(file=discord.File(random.choice('image1', 'image2', 'image3))
schedule.every(10).minutes.do(job)
while True:
schedule.run_pending()
time.sleep(1)
我知道时间表有效。但是由于某种原因,它无法发送消息。我得到这个错误:AttributeError: 'NoneType' object has no attribute 'send'
。我是编程新手,所以任何见解都将不胜感激!
解决方案
您收到该错误是因为通道变量是None
(aNoneType
没有任何属性/方法),因为通道不在内部缓存中,您阻塞了整个线程,因此它永远不会加载。我猜我可以修复您的代码,但对于后台任务来说是一个非常糟糕的解决方案。幸运discord.py
的是,它有一个内置的扩展来做这些事情,这里有一个例子:
from discord.ext import tasks
@tasks.loop(minutes=10) # You can either pass seconds, minutes or hours
async def send_image(channel: discord.TextChannel):
image = discord.File("path here")
await channel.send(file=image)
# Starting the task (you can also do it on the `on_ready` event so it starts when the bot is running)
@client.command()
async def start(ctx):
channel = client.get_channel(ID_HERE)
send_image.start(channel)
# Using the `on_ready` event
@client.event
async def on_ready():
await client.wait_until_ready() # Waiting till the internal cache is done loading
channel = client.get_channel(ID_HERE)
send_image.start(channel)
@client.command()
async def stop(ctx):
send_image.stop()
参考:
推荐阅读
- render - Qt5/Qt6 中的 Qt Quick 3D 自定义几何
- postgresql - 如何将 Markdown 数据批量插入 Postgres
- javascript - 无法在 Redux 中修改 store
- react-native - 与计算机断开连接后,React Native 应用程序无法播放 mp3
- mongodb - 可以匹配填充的嵌套数组吗?
- javascript - redux 会在任何地方更新值还是只存储数据?
- r - 根据动态模式过滤行
- google-analytics - 将谷歌搜索控制台与分析连接时出现问题
- java - 如何在 java/groovy 中解析带有 html 内容的 xml 作为值
- r - 使用 dplyr 按行用以前的值填充缺失值