簡體   English   中英

如果在 discord.py 中一段時間未使用命令,如何讓我的機器人執行某些操作?

[英]How do I make my bot do something if a command hasn't been used for awhile in 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)```

您可以使用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 參考

您可以使用Jacob Lee 指定的任務並添加一個額外的元素來檢查是否使用了 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)

參考:-

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM