Mint-Berry Dragon
Mint-Berry Dragon

Reputation: 1

(discord.py) Client.send_message() doesn't send a message

I'm using discord.py to create a chat-bot. As of now, it's only a test and all the code is in 1 file.

The bot connects to the server and listens for messages starting with an Exclamation mark '!'.

Depending on the command, it then calls one of 2 functions. Up to this point, the bot works as intended.

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)

And this is where it gets weird. When the quit-function is called, the program terminates. When the test-function is called, it does nothing. It doesn't even print the string.

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

What am i missing? Any help is appreciated.

Upvotes: 0

Views: 5006

Answers (2)

Milan Donhowe
Milan Donhowe

Reputation: 303

I got your script to function by making some of the function asynchronous and the send_message a co-routine. Of course, I'm using python 3.5 so if you're using python 3.4 you might have to do something a bit different.

I think that the reason you're message wasn't being sent was because none of your program was blocking for various functions (not using await) which can cause your bot to freeze. You can read more about it on the "What is a coroutine?" section of the discord.py docs.

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

Upvotes: 1

louis
louis

Reputation: 31

I had this exact problem, and this seemed to fix it. If you're using python 3.5:

@client.async_event
def on_message(message):

should be changed to:

@client.event
async def on_message(message):

and yield from should be changed to await. If you're not using python 3.5, I suggest upgrading to it. Hopefully this should work.

Upvotes: 3

Related Questions