Twitter Direct Messages like a Pro (with Tweepy)


Twitter Direct Messages like a Pro (with Tweepy)

Direct Messages have been available for a while on Twitter. This is not a surprise as messaging has undoubtedly a huge impact on the way we communicate, work and connect every day.

On Social Platforms messaging can play a pivotal role for businesses that want to extend their reach (increase followers), create a unique brand or deliver ‘not-less-than-excellence’ through their customer experience and support.

Photo by Oleg Magni on Unsplash

Here 1) I will discuss a few facts and considerations on how Direct Private Messages can deliver value to a brand or an organisation, 2) I will dive into some technical examples (for the techies 🤓 out there) on how a Twitter BOT can read and send DMs using Tweepy.


Value of Direct Messages

DMs can be adopted for pursuing different objectives:

  • cherish your follower base: any new follower can be welcomed with a “Thank you for following us!” message

  • engagement: send a message to followers to inform them about something important (changes in services or policies) or a new opportunity (available offers or useful tips)

  • personal: reaching privately in a friendly and personal way can create a connection between the brand and the followers

  • exploit the capabilities: Twitter DMs support up to 10k characters which allows customers to submit their queries without the constraint of a standard Tweet (max 280 chars)

Direct Messages should not be abused as they will turn into Spam pushing interest away and casting a dark shadow over the image of the brand. For the same reason, they should not be ignored or considered a low priority with late or poor responses.

Finally, when ready and committed, enable the option to receive DMs from everyone: this is important when the goal is allowing customers and users to be able to reach you.

Check “Allow message requests from everyone”

Snippets and Dev Practises of a Twitter Bot

Tweepy is one of the most popular libraries to access Twitter. It provides a wrapper around the Twitter REST API to simplify configuration, authentication and invocation of the endpoints.

Tweepy support for Twitter Direct Messages is great.

In the following sections we will see how to perform the following:

  • setup the access to Twitter API

  • fetch DMs sent to a Twitter account

  • send a message

  • delete a message

Authentication

The setup and authentication are straightforward. First, apply for a Twitter Developer Account on the Twitter Dev site to obtain the necessary access keys.

import tweepy

# Authenticate access
auth = tweepy.OAuthHandler("CONSUMER_KEY", "CONSUMER_SECRET")
auth.set_access_token("ACCESS_TOKEN", "ACCESS_TOKEN_SECRET")

# Create API handler
api = tweepy.API(auth)

Never hardcode tokens and credentials in the source code, but rather store them in an external file (.env) or (even better) in environment variables.

Receive a Direct Message

DMs sent to your account appear in the Messages Inbox. The Tweepy library provides a method to fetch them:

messages = api.list_direct_messages(count=5)
for message in reversed(messages):
  # who is sending?  
  sender_id = message.message_create["sender_id"]
  # what is she saying?
  text = message.message_create["message_data"]["text"]

A few remarks about the code above:

  1. The number of messages fetched by a single API call can be controlled (20 is the default, 50 is the max that can be used)

  2. The list is processed in reverse to read the most recent messages first

  3. All received and sent messages will be returned (yes, also our replies)

  4. Although the DM appears very quickly in the Twitter Messages Inbox, there is a delay before it is available via the API

More at Twitter REST API GET Direct Messages

Send a Direct Message

Sending DMs is again a simple operation:

recipient_id = "123"  # ID of the user
api.send_direct_message(recipient_id, "Hoi hoi")

It can be pretty cool to reply including a Media, maybe sending a Thank You gif or a small Intro video.

# upload media
media = api.media_upload(filename='/files/thankyou.png')
# send with media
recipient_id = "123"  # ID of the user
api.send_direct_message(recipient_id=recipient_id, text='Thank You!', attachment_type='media', attachment_media_id=media.media_id)

Note the recipient_id is the ID (number) of the Twitter user, not the username (string i.e. @beppecatanese). The numeric User ID can obtained with an API call

user = api.get_user("beppecatanese")
recipient_id = user.id_str

When replying to a DM we received the recipient_id can be found in the JSON payload of the original message

recipient_id = message.message_create["sender_id"]

More at Twitter REST API POST Direct Message

Delete a Direct Message

Deleting messaging is also convenient to clean up the Inbox but also to avoid inadvertently replying to the same message.

Note: I normally delete a message after I reply so I do not need to worry about skipping it next time I download the messages. Obviously this is not strictly necessary but it simplifies the management of the Inbox.

# delete by ID
api.destroy_direct_message(message.id)

Conclusion

Check out the source code on GitHub

For Tweepy new starters, I recommend a really good tutorial on Real Python