简体   繁体   English

关键字开始循环和结束循环

[英]Keyword starts loop and ends loop

I just started learning py today and I have a question with a discord bot im making.我今天刚开始学习 py,我对正在制作的 discord 机器人有疑问。 So I want to have a bot that spams a certain message every second or so.所以我想要一个机器人每秒左右发送一条垃圾邮件。 I have this so far.到目前为止我有这个。

import discord
from discord.ext import tasks, commands

bot = commands.Bot(command_prefix="!")

@bot.event
async def on_ready():
    await bot.wait_until_ready()
    print("Logged in as:")
    print(bot.user.name)
    print("------")
    channel = bot.get_channel(854067941632901163)
    print("Channel is:")
    print(channel) #Prints None
    get_price.start()


@tasks.loop(seconds=3)
async def get_price():
    await bot.wait_until_ready()
    channel = bot.get_channel(854067941632901163)
    print("Channel is:")
    print(channel) #Prints None
    await channel.send('Test')

@get_price.before_loop
async def before ():
    print("Before done.")

bot.run('token')

Every 3 seconds, it spams a message.每 3 秒,它会发送一条垃圾邮件。 I want it so I can say like,spam and it will trigger the bot to spam whatever message is there.我想要它,所以我可以说,垃圾邮件,它会触发机器人发送垃圾邮件。 and to stop the bot it would be like.stopspam.并停止机器人它就像.stopspam。 I've tried taking other bits of codes but none of them have worked.我尝试过使用其他一些代码,但它们都没有奏效。 Again yes I an very new so take it easy on me lol.再次是的,我是一个非常新的人,所以对我来说放轻松,哈哈。

Just make two commands that will use start() and cancel() .只需制作两个将使用start()cancel()的命令。 Example:例子:

@bot.command()
async def start(ctx):
    loop.start()


@bot.command()
async def stop(ctx):
    loop.cancel()


@tasks.loop(seconds=3)
async def loop():
    # your loop code here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM