Bot.Messenger
1.0.0
Facebook 메신저 봇 용 .NET 프레임 워크 라이브러리
nuget 패키지 https://www.nuget.org/packages/bot.messenger
샘플 webapi 프로젝트 https://github.com/olisamaduka/messengerbot-webapi
Facebook Messenger (WebHooks 포함)에서 봇 설정에 대한 자세한 방법과 함께 Messenger 자격 증명을 생성하려면 Facebook https://developers.facebook.com/docs/messenger-platform/guides/quick-start 에서이 빠른 스타트 가이드를 참조하십시오.
Bot . Messenger . MessengerPlatform bot = Bot . Messenger . MessengerPlatform . CreateInstance (
Bot . Messenger . MessengerPlatform . CreateCredentials ( _appSecret , _pageToken , _verifyToken ) ) ;또는 web.config에서 자격 증명을 설정하고 코드로 초기화하십시오.
web.config
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="Bot.Messenger.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<Bot.Messenger.Settings>
<setting name="PageToken" serializeAs="String">
<value>page token</value>
</setting>
<setting name="AppSecret" serializeAs="String">
<value>app secret</value>
</setting>
<setting name="VerifyToken" serializeAs="String">
<value>hello</value>
</setting>
</Bot.Messenger.Settings>
</applicationSettings>
...
</configuration>
암호
Bot . Messenger . MessengerPlatform bot = Bot . Messenger . MessengerPlatform . CreateInstance ( ) ;
// OR
// Bot.Messenger.MessengerPlatform bot = new Bot.Messenger.MessengerPlatform();CreateInstance 메소드가 자격 증명 매개 변수없이 호출되거나 매개 변수가없는 생성자가 MessengerPlatform 클래스를 초기화하는 데 사용되는 경우 web.config applicationSettings에서 자격 증명이 가져옵니다. 이것은 bot.messenger.apibase에서 상속되는 모든 유형에 적용됩니다.
// HTTP Get endpoint to verify Webhook using the Verify Token
public HttpResponseMessage Get ( )
{
var querystrings = Request . GetQueryNameValuePairs ( ) . ToDictionary ( x => x . Key , x => x . Value ) ;
Bot . Messenger . MessengerPlatform bot = Bot . Messenger . MessengerPlatform . CreateInstance (
Bot . Messenger . MessengerPlatform . CreateCredentials ( _appSecret , _pageToken , _verifyToken ) ) ;
if ( bot . Authenticator . VerifyToken ( querystrings [ "hub.verify_token" ] ) )
{
return new HttpResponseMessage ( HttpStatusCode . OK )
{
Content = new StringContent ( querystrings [ "hub.challenge" ] , Encoding . UTF8 , "text/plain" )
} ;
}
return new HttpResponseMessage ( HttpStatusCode . Unauthorized ) ;
}
// HTTP Post endpoint to receive Webhook callbacks from Facebook Messenger
[ HttpPost ]
public async Task < HttpResponseMessage > Post ( )
{
var body = await Request . Content . ReadAsStringAsync ( ) ;
Bot . Messenger . MessengerPlatform bot = Bot . Messenger . MessengerPlatform . CreateInstance (
Bot . Messenger . MessengerPlatform . CreateCredentials ( _appSecret , _pageToken , _verifyToken ) ) ;
if ( ! bot . Authenticator . VerifySignature ( Request . Headers . GetValues ( "X-Hub-Signature" ) . FirstOrDefault ( ) , body ) )
return new HttpResponseMessage ( HttpStatusCode . BadRequest ) ;
Bot . Messenger . Models . WebhookModel webhookModel = bot . ProcessWebhookRequest ( body ) ;
foreach ( var entry in webhookModel . Entries )
{
foreach ( var evt in entry . Events )
{
if ( evt . EventType == Bot . Messenger . Models . WebhookEventType . MessageReceivedCallback )
{
await bot . SendApi . SendActionAsync ( evt . Sender . ID , Bot . Messenger . Models . SenderAction . typing_on ) ;
Bot . Messenger . Models . UserProfileResponse userProfileRsp = await bot . UserProfileApi . GetUserProfileAsync ( evt . Sender . ID ) ;
if ( evt . Message . Attachments == null )
{
await bot . SendApi . SendTextAsync ( evt . Sender . ID , $ "Hello { userProfileRsp ? . FirstName } :)" ) ;
}
else // if the user sent an image, file, sticker etc., we send it back to them
{
foreach ( var attachment in evt . Message . Attachments )
{
if ( attachment . Type != Bot . Messenger . Models . AttachmentType . fallback
&& attachment . Type != Bot . Messenger . Models . AttachmentType . location )
{
await bot . SendApi . SendTextAsync ( evt . Sender . ID , $ "Hello { userProfileRsp ? . FirstName } , you sent this and we thought it would be nice we sent it back :)" ) ;
await bot . SendApi . SendAttachmentAsync ( evt . Sender . ID , attachment ) ;
}
}
}
}
}
}
return new HttpResponseMessage ( HttpStatusCode . OK ) ;
}메신저 플랫폼의 사용자 프로필 API 및 Send API가 위에서 참조되는 방법에 주목하십시오.
bot . UserProfileApi // Messenger User Profile API reference
bot . SendApi // Messenger Send API reference
//And of course the Messenger Profile API is referenced the same way
bot . MessengerProfileApibot.authenticator 참조는 Webhook 확인 토큰 및 Webhook 콜백의 Oauth 서명을 확인하는 데 사용됩니다.
/* checks if the query string value of hub.verify_token is equal to the specified VerifyToken
in your application (either the one in web.config ApplicationSettings or the one used to initialize the
Bot.Messenger.MessengerPlatform class instance) */
bot . Authenticator . VerifyToken
/* Verifies the X-Hub-Signature header against a Sha1 encryption of your specified App secret */
bot . Authenticator . VerifySignature SendApiResponse sendQuickReplyResponse = await bot . SendApi . SendTextAsync ( evt . Sender . ID , "Are you a Developer?" , new List < QuickReply >
{
new QuickReply
{
ContentType = QuickReplyContentType . text ,
Title = "Yes" ,
Payload = "PAYLOAD_YES"
} ,
new QuickReply
{
ContentType = QuickReplyContentType . text ,
Title = "No" ,
Payload = "PAYLOAD_NO"
}
} ) ;