Send a simple DM via API

direct-messages
php

#1

Hey guys,

i’m having troubles sending a DM via api, it’s probably just a little error in the syntax but i am not that good of a coder, hopefully someone can give me a hint.

This is the library I’m using: https://phpfashion.com/twitter-for-php

And that’s how i retrieve new DMs, which works fine:

$twitter = new Twitter($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
$statuses = $twitter->request('direct_messages/events/list', 'GET', ['count' => 20]);

foreach ($statuses as $status) 
{
	foreach ($status as $stat) 
	{
	echo 'ID: '.$stat->id.' Text: '.$stat->message_create->message_data->text.'<br>';
	}
}

This is the code I have tried so far to send a DM:

try {
	$send = $twitter->request('direct_messages/events/new', 'POST', ['text' => 'hello sir', 'screen_name' => 'someusername']);

} catch (TwitterException $e) {
	echo 'Error: ' . $e->getMessage();
}

But it throws the exception:

Error: Server error #415 with answer

Any help very much appreciated,

regards
Steve


#2

You’re not sending the correct data for the POST direct_messags/events/new API.


#3

thanks Abraham. I have checked the site before and tried a lot, but i’m too much of a noob to apply it. Could you tell me how i have to change my example code to make it work?

thanks so much,
Steve


#4

One change is easy, the data you are sending. In theory it would look like this:

$data = [
    'event' => [
        'type' => 'message_create',
        'message_create' => [
            'target' => [
                'recipient_id' => $userId
            ],
            'message_data' => [
                'text' => 'Hello World!'
            ]
        ]
    ]
];
$send = $twitter->request('direct_messages/events/new', $data);

But glancing at the source of that library I don’t think it supports sending JSON data to the API. You might have to switch to using TwitterOAuth.


#5

thanks a lot for taking the time. It throws an “Could not authenticate you” error, so i guess you were right about the library not supporting json data. will check out TwitterOAuth now.


closed #6

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.