Send message via Facebook Chat API (XMPP) C#
Asked Answered
A

1

88

OBSERVE https://developers.facebook.com/docs/chat/

The service and API this document covers has been deprecated with the release of Platform API v2.0. Once version 1.0 is deprecated, chat.facebook.com will no longer be available.

Important! Read this and you probably want to do something completely different than anything that has to do with this question.

I'm creating a chat with WebForms C# connecting to Facebook Chat API.

I have also looked at this SO question (and all links). Some parts are no longer relevant since Facebook requires auth_token now.

To replicate this, you should set up a Facebook web app, use the appId and a user account with xmpp_login permission set. Then create a Chat.aspx with code behind and paste this code accordingly. And replace the hard-coded users to interact with.

I have two (maybe three) issues which I believe prevent me from succeeding with my goal to send a chat message.

  1. The process noted as // finishes auth process in the documentation does not match the documentation description (I'm not getting any respones after I have received my SSL/TLS based success message from Facebook.)
  2. I have no idea how the 'send chat message'-part should be set up, and since I don't receive any messages from Facebook its hard to tell what might be wrong.

Here is my code in its entirety, on PasteBin.

I also have some helpers for adding xmpp_login permissions and such.. removed for clarity.

Global variables:

public partial class Chat : Page
{
    public TcpClient client = new TcpClient();
    NetworkStream stream;
    private SslStream ssl;
    private string AppId { get; set; }
    public string AppSecret { get; set; }
    public string AppUrl { get; set; }
    public string UserId { get; set; }
    public string AccessToken { get; set; }
    private string _error = string.Empty;//global error string for watch debugging in VS. 

    public const string FbServer = "chat.facebook.com";
    private const string STREAM_XML = "<stream:stream xmlns:stream=\"http://etherx.jabber.org/streams\" version=\"1.0\" xmlns=\"jabber:client\" to=\"chat.facebook.com\" xml:lang=\"en\" xmlns:xml=\"http://www.w3.org/XML/1998/namespace\">";
    private const string AUTH_XML = "<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='X-FACEBOOK-PLATFORM'></auth>";
    private const string CLOSE_XML = "</stream:stream>";
    private const string RESOURCE_XML = "<iq type=\"set\" id=\"3\"><bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"><resource>fb_xmpp_script</resource></bind></iq>";
    private const string SESSION_XML = "<iq type=\"set\" id=\"4\" to=\"chat.facebook.com\"><session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/></iq>";
    private const string START_TLS = "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>";

Then in Page_Load all the steps required are (or are supposed to be) performed. Worth noting is the SendMessage("test");. I just tried to put it there to see if it would succeed in sending a chat message... SetUserNameAndAuthToken sets my auth token and user name to global variables. The AuthToken works.

protected void Page_Load(object sender, EventArgs e)
{
    this.AppId = "000000082000090";//TODO get from appsettings.
    //AddAdditionalPermissions("xmpp_login");//TODO handle xmpp_login persmission
    this.AppSecret = "d370c1bfec9be6d9accbdf0117f2c495"; //TODO Get appsecret from appsetting.
    this.AppUrl = "https://fbd.anteckna.nu";

    SetUserNameAndAuthToken();

    Connect(FbServer);

    // initiates auth process (using X-FACEBOOK_PLATFORM)
    InitiateAuthProcess(STREAM_XML);

    // starting tls - MANDATORY TO USE OAUTH TOKEN!!!!
    StartTlsConnection(START_TLS);

    // gets decoded challenge from server
    var decoded = GetDecodedChallenge(AUTH_XML);

    // creates the response and signature
    string response = CreateResponse(decoded);

    //send response to server
    SendResponseToServer(response);

    SendMessage("test");

    // finishes auth process
    FinishAuthProcess();

    // we made it!
    string streamresponseEnd = SendWihSsl(CLOSE_XML);

}

So I get a response then I send the response to server:

private void SendResponseToServer(string response)
{
    string xml = String.Format("<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">{0}</response>", response);
    string response2 = SendWihSsl2(xml);
    if (!response2.ToLower().Contains("success"))
        _error = response2;
}

This takes 1 minute 40 seconds... and response is:

<success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>

Finally I do the FinishAuthPorcess()

private void FinishAuthProcess()
{
    string streamresponse = SendWithSsl(STREAM_XML);
    if (!streamresponse.Contains("STREAM:STREAM"))
        _error = streamresponse;

    string streamresponse2 = SendWihSsl(RESOURCE_XML);
    if (!streamresponse2.Contains("JID"))
        _error = streamresponse2;

    string streamresponse3 = SendWihSsl(SESSION_XML);
    if (!streamresponse3.Contains("SESSION"))
        _error = streamresponse2;
}

All responses are "". Looking at the Read method in SendWithSsl: it's 0 bytes. Trying to send a message also gives me 0 bytes Read data from Facebook. I have no clue as to why?

Armchair answered 25/10, 2013 at 13:7 Comment(18)
@DanielHilgarth Hehe, well.. the first part of Connect might not be necessary but there are no working examples of how to do this in C# so I thought I'd make sure there is one for anyone out there trying to do a facebook chat i C#. I could also write everything in one code base but then it wont be very overseeable.Armchair
If you want an answer, I suggest you strip down the code in this post to only its bare minimum required to understand the problem. The rest of the code (e.g. for others to be able to reproduce it) could you put on pastebin and link to it from your post.Ikhnaton
your code is not complete, so I cannot follow the control flow. Please attach the debug Xml, what you send to the server and what you get back. Why are you not using an existing XMPP library from here which does all teh hard work for you? xmpp.org/xmpp-software/librariesAllseed
@Allseed Here is the link from my question: pastebin.com/jst7qkrhArmchair
Maybe This would be of useCallisthenics
@Callisthenics It requires a license which would be very large based on the size of the development team as of today. Thanks anyway!Armchair
agsXMPP is GPL, jabber-net is LGPL, and when you browse the Internet you can find more XMPP c# libsAllseed
@Allseed Ok, I would need free-free since we cant make GPL...Armchair
LGPL is free, so go with jabber-net. I am very busy right now, so I can't test your code. But its very weird that the server does not reply to you for 100 seconds. I am author of 2 c# XMPP libs and have not seen this behavior before.Allseed
@MatiCicero The chat.facebook.com xmpp server is about to shut down in 6 months according to facebook.Armchair
can you provide the CreateResponse-function? i think its missing in your source.Vamoose
@Vamoose You should not go with this solution. Use a library like agsXMPP instead. However, all these solutions will stop working within six months since Facebook is shutting down the chat server.Armchair
@zeroCoder This question was an attempt to copy the PHP solution provided by Facebook. It did not work. So I scrapped the idea of using that and bought the license from ag-software. However, if you are looking at using either one you should rethink. The server used to connect facebook chat is depracted and will be offline as of spring 2015.Armchair
@zeroCoder Yes, that's exactly what's going to happen. developers.facebook.com/docs/chatArmchair
Please delete this question if it's no longer applicable, or close it as 'no longer reproducible'.Matz
...To clarify what I said a bit ago, do that once this is no longer reproducible. Or now. I mean, it's only a day anyway.Matz
I am not sure, but posting AppId, AppSecret, AppUrl is not wise on the internet, I personally hide credentials.Remington
@Remington They are not real...Armchair
C
1

There is new api now. How does the Messenger Platform work? When a person sends a message to a business on Messenger and as long as this Page uses an app to partially or fully automate conversations, the following will happen. The Facebook server sends webhooks to the URL of the business server, where the messaging app is hosted. Using the Send API, the app can respond to the person on Messenger. In this way, developers can build guided conversations to lead people through an automated flow or build an app to serve as a bridge between your agents and your business presence on Messenger.

The Messenger Platform does not require any payment to use. It is meant for businesses to handle inquiries from their customers. Once you build your experience for your customers to interact with, you can then leverage Ads to bring people to your experience, like for example Click-to-Messenger Ads or Inbox Ads.

What does a Messenger for Business experience look like? We have a sample eCommerce business that you can chat with on Messenger called Original Coast Clothing.

Chat with Sample Business Here

How do I get started? You can get started by creating a test page and test app that allows you to try your experience within Messenger. We have some examples that can get you started. Once your app is ready to deploy, you can submit it for review. When your app passes our review process, it will be ready to interact with the public.

In order to get started, you will need Messenger, a Facebook Page, and a url where the webhooks to be sent to.

Here is a step-by-step guide to deploy the above experience into your test page to get you started.

Ready to Build? Get Started

https://developers.facebook.com/products/messenger/

https://developers.facebook.com/docs/messenger-platform/reference/send-api/

Crandell answered 7/3, 2020 at 13:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.