如何在没有命令的情况下使用discord.py发送消息 [英] How to send a message with discord.py without a command

查看:143
本文介绍了如何在没有命令的情况下使用discord.py发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.当有人输入他的名字并按确定"时,我的不和谐机器人应发送一条消息.基本上我以为我用它的名字叫异步,没有用.然后我做了一个事件循环.与print()一起工作,但是机器人没有发送消息,所以我认为它还没有准备好,当我把wait_until_ready()放到那里时,它什么也没执行,所以我认为我必须把client.run("token )在事件循环之前也没有用.

Hi, i want to make a GUI. When someone put in his name and press "OK" my discord bot should send a message. Basically i thought i call the async by it's name, didn't work. Then i made a event loop. worked with a print(), but the bot doesn't send a message, so i thought it is not ready, when i put wait_until_ready() there it executed nothing, so i thought i have to put the client.run("token") before the event loop, didn't work either.

你们能帮我吗? :)

推荐答案

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

The reason your code is not working is because client.run is blocking, meaning that nothing after it will execute. This means your loop will never be reached.

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

To get around this, use client.loop.create_task.

discord.py的github有一个后台任务的示例,位于

The github of discord.py has an example of a background task, found here. You should be able to use this as reference. Currently the task posts a message to the given channel every minute, but you can easily modify it to wait for a specific action.

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')

这篇关于如何在没有命令的情况下使用discord.py发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆