Search code examples
pythonpython-3.xtwitterbotstwitter-oauth

Use twitter api to send direct messages using python


I am developing a python script to send direct messages to anyone on twitter using python.For that i am using twitter api but i dont know how to that.If anybody knows any method please help me.


Solution

  • See TwitterAPI

    from TwitterAPI import TwitterAPI
    import json
    
    api = TwitterAPI(<consumer key>, 
                     <consumer secret>,
                     <access token key>,
                     <access token secret>)
    
    user_id = <user id of the recipient>
    message_text = <the DM text>
    
    event = {
        "event": {
            "type": "message_create",
            "message_create": {
                "target": {
                    "recipient_id": user_id
                },
                "message_data": {
                    "text": message_text
                }
            }
        }
    }
    
    r = api.request('direct_messages/events/new', json.dumps(event))
    print('SUCCESS' if r.status_code == 200 else 'PROBLEM: ' + r.text)