如果在 discord.py 中一段时间​​未使用命令,如何让我的机器人执行某些操作?

时间:2021-04-13 05:22:19

标签: python discord discord.py

我想知道如果在 1 分钟内没有使用“helloworld”命令,如何让机器人在频道中说些什么

from discord.ext import commands

client = commands.Bot(command_prefix='!')

@client.event
async def on_ready():
    print('connected')

# Command
@client.command()
async def helloworld(ctx):
    await ctx.send('Hello World!')

client.run(TOKEN)```

2 个答案:

答案 0 :(得分:0)

您可以使用 discord.ext.tasks。我不确定它是否可以用作命令(因为命令需要调用),但是,给定通道 ID,您可以在一段时间内重复将消息发送到指定的通道。

from discord.ext import commands
from discord.ext import tasks

client = commands.Bot(command_prefix='!')

@client.event
async def on_ready():
    print('connected')

@tasks.loop(seconds=5.0)
async def helloworld(channel_id=1234567890):
    channel = await client.fetch_channel(channel_id)
    await channel.send("Hello World!")


client.run(TOKEN)

传递给 tasks.loop() 装饰器的时间间隔参数可以是 seconds=minutes=hours=

discord.ext.tasks API Reference

答案 1 :(得分:0)

您可以使用像 Jacob Lee specified 这样的任务并添加一个额外的元素来检查是否使用了 hello world。

import json
from datetime import datetime
@client.event
async def on_command_completion(ctx):
    if ctx.command.name == 'helloworld':
         with open('invoke.json', 'r') as f:
               data = json.load(f)
         data['time'] = datetime.now().strftime('%y-%m-%d-%H-%M-%S')
         with open('invoke.json', 'w') as f:
               json.dump(data, f, indent=4)

@tasks.loop(seconds=10)
async def check_hello():
    with open('invoke.json', 'r') as f:
        data = json.load(f)
    if 'time' in data.keys():
        if (datetime.now() - datetime.strptime(data['time'], '%y-%m-%d-%H-%M-%S')).total_seconds() > 60:
            if 'last_invoked' in data.keys():
                if datetime.strptime(data['last_invoked'], '%y-%m-%d-%H-%M-%S') > datetime.strptime(data['time'], '%y-%m-%d-%H-%M-%S'): 
                    return 
                channel = await client.fetch_channel(channel_id)
                await channel.send("Hello has not been used in a minute")
                data['last_invoked'] = datetime.now().strftime('%y-%m-%d-%H-%M-%S')
                with open('invoke.json', 'w') as f:
                    json.dump(data)

参考文献:-