Git Product home page Git Product logo

pymessenger's Introduction

pymessenger Build Status

Python Wrapper for Facebook Messenger Platform.

Disclaimer: This wrapper is NOT an official wrapper and do not attempt to represent Facebook in anyway.

About

This wrapper has the following functions:

  • send_text_message(recipient_id, message)
  • send_message(recipient_id, message)
  • send_generic_message(recipient_id, elements)
  • send_button_message(recipient_id, text, buttons)
  • send_attachment(recipient_id, attachment_type, attachment_path)
  • send_attachment_url(recipient_id, attachment_type, attachment_url)
  • send_image(recipient_id, image_path)
  • send_image_url(recipient_id, image_url)
  • send_audio(recipient_id, audio_path)
  • send_audio_url(recipient_id, audio_url)
  • send_video(recipient_id, video_path)
  • send_video_url(recipient_id, video_url)
  • send_file(recipient_id, file_path)
  • send_file_url(recipient_id, file_url)
  • send_action(recipient_id, action)
  • send_raw(payload)
  • get_user_info(recipient_id)
  • set_get_started(gs_obj)
  • set_persistent_menu(pm_obj)
  • remove_get_started()
  • remove_persistent_menu()

You can see the code/documentation for there in bot.py.

The functions return the full JSON body of the actual API call to Facebook.

Register for an Access Token

You'll need to setup a Facebook App, Facebook Page, get the Page Access Token and link the App to the Page before you can really start to use the Send/Receive service.

This quickstart guide should help

Installation

pip install pymessenger

Usage

from pymessenger.bot import Bot

bot = Bot(<access_token>, [optional: app_secret])
bot.send_text_message(recipient_id, message)

Note: From Facebook regarding User IDs

These ids are page-scoped. These ids differ from those returned from Facebook Login apps which are app-scoped. You must use ids retrieved from a Messenger integration for this page in order to function properly.

If app_secret is initialized, an app_secret_proof will be generated and send with every request. Appsecret Proofs helps further secure your client access tokens. You can find out more on the Facebook Docs

Sending a generic template message:

Generic Template Messages allows you to add cool elements like images, text all in a single bubble.

from pymessenger.bot import Bot
bot = Bot(<access_token>)
elements = []
element = Element(title="test", image_url="<arsenal_logo.png>", subtitle="subtitle", item_url="http://arsenal.com")
elements.append(element)

bot.send_generic_message(recipient_id, elements)

Output:

Generic Bot Output

Sending an image/video/file using an URL:
from pymessenger.bot import Bot
bot = Bot(<access_token>)
image_url = "http://url/to/image.png"
bot.send_image_url(recipient_id, image_url)

Todo

  • Structured Messages
  • Receipt Messages
  • Quick Replies
  • Airlines
  • Tests!

Example

Screenshot of Echo Facebook Bot

You can find an example of an Echo Facebook Bot in examples/

pymessenger's People

Contributors

biw avatar crashburn65 avatar cretezy avatar davidmann4 avatar drice avatar h4ck3rk3y avatar madewithkode avatar mohitbansal964 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pymessenger's Issues

NON_PROMOTIONAL_SUBSCRIPTION

From 1 january 2019 all messages sent outside the 24 hour window need to have the tag NON_PROMOTIONAL_SUBSCRIPTION and the messaging_type TYPE_MESSAGE_TAG.

Facebook Messenger (Python) two different results same user

The problem is exactly the same here: https://stackoverflow.com/questions/41601267/facebook-messenger-python-two-different-results-same-user

And I can confirm this comment: "facebook's api posts back the message with the recipientID of the facebook page's ID. I know kinda weird. My guess is that you (user1) populates that list, but somewhere in between (user2 being the facebook page) also contributes to the length of the list.. idk, just a guess. what do you think? try printing out recipient IDs."

I am using Flask and Heroku for webhook server.
What should I do?

sometime why it's giving replay 2-3 times ?

it was working good. But on heavy load it gives same replay 3-4 times. i am new to python, for a library i needed to rewrite the whole thing from Nodejs to python. Now, the response is slow in heavy load, and sometime i see same response 2-3 times. Can anyone help to let me know what's wrong im doing?
Or any suggestion to make it better?

def hello():
    if request.method == 'GET':
        if request.args.get("hub.verify_token") == VERIFY_TOKEN:
            return request.args.get("hub.challenge")
        else:
            return 'Invalid verification token'
    try:
        if request.method == 'POST':
            output = request.get_json()
            print(output)
            for event in output['entry']:
                if event.get("messaging"):
                    messaging = event['messaging']
                    for x in messaging:
                        if x.get('message'):
                            recipient_id = x['sender']['id']
                            if x['message'].get('text'):
                                message = emoji.demojize(
                                    x['message']['text'])
                                message = message[1:300]  # slice character
                                #----------------------some other code----------------
                                if  condition
                                    similar = findSimilar(message)
                                    if similar != False:
                                        bot.send_text_message(recipient_id,
                                                              "Unkonwn words. Some similar words - \n => "+similar)
                                    else:
                                        bot.send_text_message(
                                            recipient_id, "Unknown word/sentence. No similar words found")
                                else:
                                    bot.send_text_message(
                                        recipient_id, translation)
                                if x['message'].get('attachments'):
                                    bot.send_text_message(
                                        recipient_id, "No result!!")
                        else:
                            return "Success"
                return "Success"
        return "Success"

License

Hey,

Seems like this project doesn't have a license. Do you think we should add one? MIT would be a nice fit for this I'd find.

unhashable type: 'dict' with send_attachment

hi.
recieving error unhashable type: 'dict' with send_attachment and send_image functions.


  File "D:\projects\Test\bot.py", line 71, in send_attachment
    'id': recipient_id

TypeError: unhashable type: 'dict'

print(recipient_id, attachment_type,attachment_path):
1336772359690730 image d:\projects\Test\logo.png

send_attachment_url and other functions works fine
Thank you in advance

Fork for this repo

Somebody have a fork for this repo with updates? The last updated version in PyPi is in 2016, pull request for quick replies pending and Issues pending to close.

I'm very grateful with David for this repo, but, I think this project need updates with urgency.

Maintenance

I think this is an interesting project but a lot of PRs and issues don't seem to get the attention they need which usually leads to contriutor frustration, I'd be willing to contribute but not if things won't get merged eventually.

@davidchua are you the only maintainer? @Cretezy seems to be quite active too.
Why are the builds failing on master and nobody seems to care?
And finally is it worth my time to contribute or should I fork it? I could possibly help maintaining things related to features I need but I can't make promises at this stage.

use of enum breaks python2

Python 3 has enum included by default, but Python 2 does not.

To have this work with pip, I suggest we modify the setup.py to the following:

install_requires = [
'requests',
'requests-toolbelt',
'six'
]

try:
import enum
except ImportError:
install_requires.append('enum')

how to use set_get_started method?

I am trying to invoke a greeting message once the user open the massenger , I see that set_get_started is present but I can't see it when I write bot.set_get_started it gives error so how can I use to to invoke greeting text?

Element Python3

Just a heads up had to edit the Element class to work for my bot as iteritems does not exist in python3.
I'm sure in the init you can add a case for Python3 to use .items() .

For my use case I just skipped importing Element and defined it in my Django View.
class Element(dict):
acceptable_keys = ['title', 'item_url', 'image_url', 'subtitle', 'buttons']
def __init
(self, _args, *_kwargs):
kwargs = {k:v for k, v in kwargs.items() if k in self.acceptable_keys}
super(Element, self).__init
(_args, *_kwargs)

AttributeError 'Bot' object has no attribute 'base_url' for bot.send_image

Hi, I wanted to send an image as a file, not via url, but got an AttributeError 'Bot' object has no attribute 'base_url' for bot.send_image.

Traceback (most recent call last):
  File "paul.py", line 166, in webhook
    bot.send_image(sender_id, generated_image)
  File "/home/psuser/paul/paul/local/lib/python2.7/site-packages/pymessenger/bot.py", line 135, in send_image
    return requests.post(self.base_url, data=multipart_data, headers=multipart_header).json()
AttributeError: 'Bot' object has no attribute 'base_url'

`unicode` is not defined in python 3

In utils.py there is still one line that uses unicode() which will fail in python3. Patch:

@@ -17,7 +17,10 @@ def validate_hub_signature(app_secret, r
         pass
     else:
         digest_module = getattr(hashlib, hash_method)
-        hmac_object = hmac.new(str(app_secret), unicode(request_payload), digest_module)
+        if six.PY2:
+                hmac_object = hmac.new(str(app_secret), unicode(request_payload), digest_module)
+        else:
+                hmac_object = hmac.new(bytearray(app_secret, 'utf8'), request_payload, digest_module)
         generated_hash = hmac_object.hexdigest()
         if hub_signature == generated_hash:
             return True

Sending a message to group chat

Right now pymessenger supports sending message to one user only. There should be feature by which we can message a group chat

Send sticker

It always send sticker as a image, like the following screen shot. Could it send a sticker?
And when I use send_raw() to send a sticker, it'll give me an error.

default

Getting user info and Get Started

I was digging through the code and noticed a get_user_info method for getting the Facebook info for a given sender, however when I call it, I get an error that it is not part of the bot class.
Examples of how I've tried to call it
user_info = bot.get_user_info(recipient_id, fields=None)
user_info = bot.get_user_info(bot, recipient_id, fields=None)

Also, does this wrapper yet support having a Get Started and/or persistent menu?

How to get attachment URL

When i try to get attachement application is stuck, not respone after sending attachement.

bot.send_attachment_url(recipient_id, att['type'], att['payload']['url'])

### ERROR:
127.0.0.1 - - [09/May/2019 13:18:18] "POST / HTTP/1.1" 500 - Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1997, in __call__ return self.wsgi_app(environ, start_response) File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1985, in wsgi_app response = self.handle_exception(e) File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1540, in handle_exception reraise(exc_type, exc_value, tb) File "/usr/local/lib/python3.5/dist-packages/flask/_compat.py", line 33, in reraise raise value File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "/usr/local/lib/python3.5/dist-packages/flask/_compat.py", line 33, in reraise raise value File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/home/duka/fb_chat_bot/app.py", line 35, in hello bot.send_attachment_url(recipient_id, att['type'], att['payload']['url']) AttributeError: 'Bot' object has no attribute 'send_attachment_url'

python3 support?

is this module available for python3?

Also tried import Bot but got issues:

>> from pymessenger import Bot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name Bot

pymessenger.Element is not JSON serializable

Hi

I'm trying to use the send_generic_message function but am getting an error pymessenger.Element is not JSON serializable

elements = []
element = Element(title="test", image_url="<arsenal_logo.png>", subtitle="subtitle", item_url="http://arsenal.com")
elements.append(element)
bot.send_generic_message(id, elements)

Here is my pip freeze output:

coverage==3.7.1
decorator==4.0.9
ecdsa==0.10
Fabric==1.8.2
feedparser==5.2.1
Flask==0.10.1
Flask-SQLAlchemy==1.0
Flask-WTF==0.9.4
gunicorn==19.3.0
itsdangerous==0.23
Jinja2==2.7.2
MarkupSafe==0.18
paramiko==1.12.2
pycrypto==2.6.1
pymessenger==0.0.4.0
requests==2.10.0
requests-toolbelt==0.6.2
six==1.10.0
SQLAlchemy==0.9.3
validators==0.10.1
Werkzeug==0.9.4
WTForms==1.0.5

Issue with the Echo Bot

Actual Code : bot.send_text_message(recipient_id, response) ๐Ÿ‘Ž
Working Code : bot.send_text_message(sender_id, response) ๐Ÿ‘

can you receive messages back from a user?

It isn't clear from the README, but can you receive messages from a user and respond based on keywords in the response? Or is the code mainly for sending notifications?

Adding A Button To Generic Template

Is there a way to add a button to the generic view with the wrapper as it stands? I tried including a tuple in the generic view list with a button, but that didn't seem to do it.

get_user_info does not work with requests module properly

    def get_user_info(self, recipient_id, fields=None):
        """Getting information about the user
        https://developers.facebook.com/docs/messenger-platform/user-profile
        Input:
          recipient_id: recipient id to send to
        Output:
          Response from API as <dict>
        """
        params = {}
        if fields is not None and isinstance(fields, (list, tuple)):
            params['fields'] = ",".join(fields)

        params.update(self.auth_args)

        request_endpoint = '{0}/{1}'.format(self.graph_url, recipient_id)
        response = requests.get(request_endpoint, params=params)
        if response.status_code == 200:
            return response.json()

        return None

When passing params in func get_user_info(), module requests interprets the string with passed parameters and changes all commas to comma escape character.
In the end, the URL part with passed parameters ['time_zone', 'first_name'] looks like this: fields=time_zone%2Cfirst_name, but in messenger API it should look like this: fields=time_zone,first_name

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.