1+ import base64
2+ import hashlib
3+ import os
4+ import re
5+ import json
6+ import requests
7+ from requests_oauthlib import OAuth2Session
8+
9+ # This example is set up to retrieve Direct Message conversation events associated with a one-to-one message.
10+ # Currently, the v2 DM endpoints support three conversation event types: MessageCreate, ParticipantsJoin, and
11+ # ParticipantsLeave.
12+ GET_DM_EVENTS_URL = "https://api.twitter.com/2/dm_conversations/with/:participant_id/dm_events"
13+
14+ #-----------------------------------------------------------------------------------------------------------------------
15+ # These variables need to be updated to the setting that match how your Twitter App is set-up at
16+ # https://developer.twitter.com/en/portal/dashboard. These will not change from run-by-run.
17+ client_id = 'dE5vYmJaa3o5QWRlNEt1T01DZ206MTpjaQ'
18+ #This must match *exactly* the redirect URL specified in the Developer Portal.
19+ redirect_uri = "https://www.example.com"
20+ #-----------------------------------------------------------------------------------------------------------------------
21+ # This variable indicates the participant of the one-to-one conversation. A more ready-to-be used example would
22+ # have this passed in from some calling code.
23+ # Who is this one-to-one conversation with?
24+ participant_id = "906948460078698496"
25+ #-----------------------------------------------------------------------------------------------------------------------
26+
27+ def handle_oauth ():
28+
29+ # Set the scopes needed to be granted by the authenticating user.
30+ scopes = ["dm.read" , "tweet.read" , "users.read" , "offline.access" ]
31+
32+ # Create a code verifier
33+ code_verifier = base64 .urlsafe_b64encode (os .urandom (30 )).decode ("utf-8" )
34+ code_verifier = re .sub ("[^a-zA-Z0-9]+" , "" , code_verifier )
35+
36+ # Create a code challenge
37+ code_challenge = hashlib .sha256 (code_verifier .encode ("utf-8" )).digest ()
38+ code_challenge = base64 .urlsafe_b64encode (code_challenge ).decode ("utf-8" )
39+ code_challenge = code_challenge .replace ("=" , "" )
40+
41+ # Start and OAuth 2.0 session
42+ oauth = OAuth2Session (client_id , redirect_uri = redirect_uri , scope = scopes )
43+
44+ # Create an authorize URL
45+ auth_url = "https://twitter.com/i/oauth2/authorize"
46+ authorization_url , state = oauth .authorization_url (
47+ auth_url , code_challenge = code_challenge , code_challenge_method = "S256"
48+ )
49+
50+ # Visit the URL to authorize your App to make requests on behalf of a user
51+ print (
52+ "Visit the following URL to authorize your App on behalf of your Twitter handle in a browser:"
53+ )
54+ print (authorization_url )
55+
56+ # Paste in your authorize URL to complete the request
57+ authorization_response = input (
58+ "Paste in the full URL after you've authorized your App:\n "
59+ )
60+
61+ # Fetch your access token
62+ token_url = "https://api.twitter.com/2/oauth2/token"
63+
64+ # The following line of code will only work if you are using a type of App that is a public client
65+ auth = False
66+
67+ token = oauth .fetch_token (
68+ token_url = token_url ,
69+ authorization_response = authorization_response ,
70+ auth = auth ,
71+ client_id = client_id ,
72+ include_client_id = True ,
73+ code_verifier = code_verifier ,
74+ )
75+
76+ # Your access token
77+ access = token ["access_token" ]
78+
79+ return access
80+
81+ def get_one_to_one_conversation_events (participant_id ):
82+
83+ access = handle_oauth ()
84+
85+ headers = {
86+ "Authorization" : "Bearer {}" .format (access ),
87+ "Content-Type" : "application/json" ,
88+ "User-Agent" : "TwitterDevSampleCode" ,
89+ "X-TFE-Experiment-environment" : "staging1" ,
90+ "Dtab-Local" : "/s/gizmoduck/test-users-temporary => /s/gizmoduck/gizmoduck"
91+ }
92+
93+ request_url = GET_DM_EVENTS_URL .replace (':participant_id' , str (participant_id ))
94+
95+ response = requests .request ("GET" , request_url , headers = headers )
96+
97+ if response .status_code != 200 :
98+ print ("Request returned an error: {} {}" .format (response .status_code , response .text ))
99+ else :
100+ print (f"Response code: { response .status_code } " )
101+ return response
102+
103+ def main ():
104+ response = get_one_to_one_conversation_events (participant_id )
105+ print (json .dumps (json .loads (response .text ), indent = 4 , sort_keys = True ))
106+
107+ if __name__ == "__main__" :
108+ main ()
0 commit comments