首页 文章

如何在没有命令的情况下使用discord.py发送消息

提问于
浏览
0
import discord
import asyncio

client = discord.Client()
@client.event
async def on_ready():
    print("I'm ready.")

async def send(message):
    await client.send_message(client.get_channel("412678093006831617"), message)

client.run("token")

loop = asyncio.get_event_loop()
loop.run_until_complete(send("hello"))

嗨,我想制作一个GUI . 当有人输入他的名字并按“OK”时,我的不和谐机器人应该发送一条消息 . 基本上我以为我用它的名字称为异步,不起作用 . 然后我做了一个事件循环 . 使用print(),但机器人不发送消息,所以我认为它没有准备好,当我把wait_until_ready()放在那里它没有执行任何东西,所以我想我必须把client.run(“令牌“)在事件循环之前,也没有工作 .

你们能帮助我吗? :)

2 回答

  • 0

    对于响应行为,您有两个选择:您可以编写 on_message 事件处理程序,或使用 discord.ext.commands 模块 . 我建议使用 commands ,因为它将所有内容保存在一个协同程序中 .

    from discord.ext.commands import Bot
    
    bot = Bot(command_prefix='!')
    
    @bot.event
    async def on_ready():
        print("I'm ready.")
        global target_channel
        target_channel = bot.get_channel("412678093006831617")
    
    @bot.command()
    async def send(*, message)
        global target_channel
        await bot.send_message(channel, message)
    

    这将使用 !send Some message 调用 . *, message 语法只是告诉机器人不要尝试进一步解析消息内容 .

  • 3

    您的代码无法正常工作的原因是因为 client.run 正在阻塞,这意味着它不会执行任何操作 . 这意味着永远不会到达 loop .

    要解决此问题,请使用 client.loop.create_task .

    discord.py 的github有一个后台任务的例子,找到here . 您应该可以将此作为参考 . 目前,该任务每分钟都会向给定 Channels 发送一条消息,但您可以轻松修改该消息以等待特定操作 .

    import discord
    import asyncio
    
    client = discord.Client()
    
    async def my_background_task():
        await client.wait_until_ready()
        counter = 0
        channel = discord.Object(id='channel_id_here')
        while not client.is_closed:
            counter += 1
            await client.send_message(channel, counter)
            await asyncio.sleep(60) # task runs every 60 seconds
    
    @client.event
    async def on_ready():
        print('Logged in as')
        print(client.user.name)
        print(client.user.id)
        print('------')
    
    client.loop.create_task(my_background_task())
    client.run('token')
    

相关问题