(discord.py)Client.send_message()不发送消息

时间:2016-10-10 16:43:38

标签: python python-3.x

我正在使用discord.py创建一个聊天机器人。截至目前,它只是一个测试,所有代码都在1个文件中。

僵尸程序连接到服务器并侦听以感叹号'!'开头的消息。

根据命令,它会调用2个函数之一。到目前为止,机器人按预期工作。

client = discord.Client()

@client.async_event
def on_message(message):
    author = message.author
    if message.content.startswith('!test'):
        print('on_message !test')
        test(author, message)
    if message.content.startswith('!quit'):
        print('on_message !quit')
        quit(author, message)

这就是它变得奇怪的地方。调用quit-function时,程序终止。调用测试函数时,它什么都不做。它甚至不打印字符串。

def test(author, message):
    print('in test function')
    yield from client.send_message(message.channel, 'Hi %s, i heard you.' % author)

def quit(author, message):
    sys.exit()

我缺少什么?任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:2)

我遇到了这个问题,这似乎解决了这个问题。如果你正在使用python 3.5:

@client.event
async def on_message(message):

应更改为:

yield from

await应更改为@Transactional。如果您不使用python 3.5,我建议升级到它。希望这应该有用。

答案 1 :(得分:1)

我让你的脚本通过使一些函数异步并且send_message成为一个协同例程来运行。当然,我正在使用python 3.5,所以如果你使用的是python 3.4,你可能需要做一些不同的事情。

认为 您没有发送消息的原因是因为您的程序没有阻止各种功能(不使用等待),这可能导致你的机器人要冻结。您可以在discord.py文档的"What is a coroutine?"部分了解有关它的更多信息。

client = discord.Client()

@client.async_event
async def on_message(message):
    author = message.author
    if message.content.startswith('!test'):
        print('on_message !test')
        await test(author, message)
    if message.content.startswith('!quit'):
        print('on_message !quit')
        quit(author, message)
async def test(author, message):
    print('in test function')
    await client.send_message(message.channel, 'Hi %s, i heard you.' % author)

def quit(author, message):
    sys.exit()