通过Facebook Chat API(XMPP)C#发送消息 [英] Send message via Facebook Chat API (XMPP) C#

查看:104
本文介绍了通过Facebook Chat API(XMPP)C#发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

观察 https://developers.facebook.com/docs/chat/

Platform API v2.0发行版已弃用该文档涵盖的服务和API.版本1.0被弃用后,chat.facebook.com将不再可用.

重要!阅读此书,您可能想要做与该问题完全不同的事情.

我正在使用连接到Facebook Chat API的WebForms C#创建聊天.

我还查看了此问题(以及所有链接).由于Facebook现在需要auth_token,因此某些部分不再相关.

要复制此内容,您应该设置一个Facebook Web应用程序,使用appId和设置了xmpp_login权限的用户帐户.然后创建后面带有代码的Chat.aspx并相应地粘贴此代码.并替换与之进行交互的硬编码用户.

我遇到了两个(也许三个)问题,这些问题使我无法成功实现发送聊天消息的目标.

  1. 文档中标记为// finishes auth process的过程与文档描述不符 (从Facebook收到基于SSL/TLS的成功消息后,我没有得到任何回复.)
  2. 我不知道应该如何设置发送聊天消息"部分,并且由于我没有收到来自Facebook的任何消息,因此很难说出可能是什么问题.

这是我在PasteBin上的全部代码.

我还提供了一些用于添加xmpp_login权限的帮助器,为清楚起见,已将其删除..

全局变量:

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\"/>";

然后在(c4)中执行(或应该执行)所有必需的步骤.值得注意的是SendMessage("test");.我只是尝试将其放在此处,以查看它是否可以成功发送聊天消息... SetUserNameAndAuthToken将我的身份验证令牌和用户名设置为全局变量. AuthToken有效.

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);

}

所以我得到一个响应,然后将响应发送到服务器:

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;
}

这需要1分40秒...并且响应为:

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

最后我执行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;
}

所有答复均为"".在SendWithSsl中查看Read方法:它是0个字节. 尝试发送一条消息也给了我0个字节从Facebook读取数据.我不知道为什么吗?

解决方案

现在有新的api. Messenger平台如何工作? 当某人在Messenger上向企业发送消息时,只要此页面使用应用程序部分或完全自动化对话,就会发生以下情况. Facebook服务器将Webhook发送到托管消息传递应用程序的业务服务器的URL.使用Send API,应用程序可以在Messenger上回复该人.通过这种方式,开发人员可以建立引导性的对话,以引导人们通过自动流程,或者构建一个应用程序,以充当您的代理与Messenger上的企业形象之间的桥梁.

Messenger平台不需要任何付款即可使用.它旨在使企业处理来自客户的查询.建立与客户互动的体验后,您就可以利用广告将人们带入您的体验中,例如,点击信使广告或收件箱广告.

Messenger for Business体验是什么样的? 我们有一个示例电子商务业务,您可以在Messenger上与它聊天,称为原始海岸服装".

在此处进行示例业务的聊天

我如何开始? 您可以通过创建一个测试页和测试应用程序开始使用,该程序可以让您尝试在Messenger中体验.我们有一些示例可以帮助您入门.准备好部署您的应用程序后,您可以将其提交以供审核.当您的应用通过我们的审核过程后,即可与公众互动.

要开始使用,您将需要Messenger,Facebook页面以及将Webhook发送到的URL.

此处是将上述经验部署到测试页中的逐步指南,以帮助您入门.

准备好进行构建了吗? 开始使用

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

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

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?

解决方案

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/

这篇关于通过Facebook Chat API(XMPP)C#发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆