Skip to content

Commit 26b067e

Browse files
authored
Merge pull request #7 from tbsf/original
FIX for forgetting to import utils, add tests, add graph_api/user_profile_api
2 parents 02d342a + 1803cfc commit 26b067e

File tree

5 files changed

+122
-18
lines changed

5 files changed

+122
-18
lines changed

pymessenger/bot.py

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,16 @@
11
import json
2+
23
import requests
34
from requests_toolbelt import MultipartEncoder
45

5-
DEFAULT_API_VERSION = 2.6
6+
from pymessenger.graph_api import FacebookGraphApi
7+
import pymessenger.utils as utils
8+
69

7-
class Bot(object):
8-
def __init__(self, access_token, api_version=DEFAULT_API_VERSION, app_secret=None):
9-
self.api_version = api_version
10-
self.access_token = access_token
11-
self.base_url = (
12-
"https://graph.facebook.com"
13-
"/v{0}/me/messages?access_token={1}"
14-
).format(self.api_version, access_token)
10+
class Bot(FacebookGraphApi):
1511

16-
if app_secret is not None:
17-
appsecret_proof = generate_appsecret_proof(access_token, app_secret)
18-
self.base_url += '&appsecret_proof={0}'.format(appsecret_proof)
12+
def __init__(self, *args, **kwargs):
13+
super(Bot, self).__init__(*args, **kwargs)
1914

2015
def send_text_message(self, recipient_id, message):
2116
payload = {
@@ -72,10 +67,6 @@ def send_button_message(self, recipient_id, text, buttons):
7267
}
7368
return self._send_payload(payload)
7469

75-
def _send_payload(self, payload):
76-
result = requests.post(self.base_url, json=payload).json()
77-
return result
78-
7970
def send_image(self, recipient_id, image_path):
8071
'''
8172
This sends an image to the specified recipient.
@@ -135,3 +126,15 @@ def send_image_url(self, recipient_id, image_url):
135126
)
136127
}
137128
return self._send_payload(payload)
129+
130+
def _send_payload(self, payload):
131+
request_endpoint = '{0}/me/messages'.format(self.graph_url)
132+
response = requests.post(
133+
request_endpoint,
134+
params=self.auth_args,
135+
json=payload
136+
)
137+
result = response.json()
138+
return result
139+
140+

pymessenger/graph_api.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import pymessenger.utils as utils
2+
3+
DEFAULT_API_VERSION = 2.6
4+
5+
class FacebookGraphApi(object):
6+
def __init__(self, access_token, **kwargs):
7+
'''
8+
@required:
9+
access_token
10+
@optional:
11+
api_version
12+
app_secret
13+
'''
14+
15+
self.api_version = kwargs.get('api_version') or DEFAULT_API_VERSION
16+
self.app_secret = kwargs.get('app_secret')
17+
self.graph_url = 'https://graph.facebook.com/v{0}'.format(self.api_version)
18+
self.access_token = access_token
19+
20+
@property
21+
def auth_args(self):
22+
if not hasattr(self, '_auth_args'):
23+
auth = {
24+
'access_token': self.access_token
25+
}
26+
if self.app_secret is not None:
27+
appsecret_proof = utils.generate_appsecret_proof(self.access_token, self.app_secret)
28+
auth['appsecret_proof'] = appsecret_proof
29+
self._auth_args = auth
30+
return self._auth_args

pymessenger/user_profile.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import requests
2+
3+
from pymessenger.graph_api import FacebookGraphApi
4+
5+
class UserProfileApi(FacebookGraphApi):
6+
def get(self, user_id, fields=None):
7+
params = {}
8+
if fields is not None and isinstance(fields, (list, tuple)):
9+
params['fields'] = ",".join(fields)
10+
11+
params.update(self.auth_args)
12+
13+
request_endpoint = '{0}/{1}'.format(self.graph_url, user_id)
14+
response = requests.get(request_endpoint, params=params)
15+
if response.status_code == 200:
16+
user_profile = response.json()
17+
return user_profile
18+
return None

test/message_test.py

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
import sys, os
22
sys.path.append(os.path.realpath(os.path.dirname(__file__)+"/.."))
3+
34
from pymessenger.bot import Bot as PyBot
4-
from pymessenger import Element
5+
from pymessenger import Element, Button
56

67
TOKEN = os.environ.get('TOKEN')
7-
bot = PyBot(TOKEN)
8+
APP_SECRET = os.environ.get('APP_SECRET')
9+
10+
bot = PyBot(TOKEN, app_secret=APP_SECRET)
811
recipient_id = os.environ.get('RECIPIENT_ID')
912

1013
def test_wrong_format_message():
@@ -17,3 +20,32 @@ def test_text_message():
1720
assert type(result) is dict
1821
assert result.get('message_id') is not None
1922
assert result.get('recipient_id') is not None
23+
24+
def test_elements():
25+
image_url = 'https://lh4.googleusercontent.com/-dZ2LhrpNpxs/AAAAAAAAAAI/AAAAAAAA1os/qrf-VeTVJrg/s0-c-k-no-ns/photo.jpg'
26+
elements = []
27+
element = Element(title="Arsenal", image_url=image_url, subtitle="Click to go to Arsenal website.", item_url="http://arsenal.com")
28+
elements.append(element)
29+
result = bot.send_generic_message(recipient_id, elements)
30+
assert type(result) is dict
31+
assert result.get('message_id') is not None
32+
assert result.get('recipient_id') is not None
33+
34+
def test_image_url():
35+
image_url = 'https://lh4.googleusercontent.com/-dZ2LhrpNpxs/AAAAAAAAAAI/AAAAAAAA1os/qrf-VeTVJrg/s0-c-k-no-ns/photo.jpg'
36+
result = bot.send_image_url(recipient_id, image_url)
37+
assert type(result) is dict
38+
assert result.get('message_id') is not None
39+
assert result.get('recipient_id') is not None
40+
41+
def test_button_message():
42+
buttons = []
43+
button = Button(title='Arsenal', type='web_url', url='http://arsenal.com')
44+
buttons.append(button)
45+
button = Button(title='Other', type='postback', payload='other')
46+
buttons.append(button)
47+
text='Select'
48+
result = bot.send_button_message(recipient_id, text, buttons)
49+
assert type(result) is dict
50+
assert result.get('message_id') is not None
51+
assert result.get('recipient_id') is not None

test/user_profile_test.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import json
2+
import sys, os
3+
sys.path.append(os.path.realpath(os.path.dirname(__file__)+"/.."))
4+
5+
from pymessenger.user_profile import UserProfileApi
6+
7+
TOKEN = os.environ.get('TOKEN')
8+
APP_SECRET = os.environ.get('APP_SECRET')
9+
TEST_USER_ID = os.environ.get('RECIPIENT_ID')
10+
11+
upa = UserProfileApi(TOKEN, app_secret=APP_SECRET)
12+
13+
def test_fields_blank():
14+
user_profile = upa.get(TEST_USER_ID)
15+
assert user_profile is not None
16+
17+
def test_fields():
18+
fields = ['first_name', 'last_name']
19+
user_profile = upa.get(TEST_USER_ID, fields=fields)
20+
assert user_profile is not None
21+
assert len(user_profile.keys()) == len(fields)

0 commit comments

Comments
 (0)